Returning focus after a tour closes
Capturing the pre-tour focus target
When a tour closes — whether the user finishes the last step, clicks "Close", or presses Escape — focus must return to the element that had it before the tour opened. If focus lands on <body> the keyboard user loses their place and must Tab through the entire page again.
At tour start, store a reference:
const previousFocus = document.activeElement;
If previousFocus is <body> or null, fall back to the first focusable element in the main content area (main, [role="main"], or #content).
Restoring focus after every exit path
Attach a single cleanup function that runs on:
- "Finish" button click
- "Close" button click
- Escape key press
- Programmatic tour.end() call
The function:
function restoreFocus() {
if (previousFocus && typeof previousFocus.focus === 'function') {
previousFocus.focus();
} else {
fallbackFocus();
}
}
Ensure the tooltip and its backdrop are removed from the DOM before calling restoreFocus() so the focus ring appears on the correct element.
Worked example: focus lost on Escape
Before – User opens tour from a "Help" button in the header. They press Escape on step 2. Focus jumps to <body>. Screen reader announces "Blank". User must Tab 12 times to reach the main navigation.
After – Tour start captures the "Help" button as previousFocus. Escape triggers cleanup(), tooltip removes, previousFocus.focus() runs. Focus returns to the "Help" button; screen reader announces "Help button". Verification: open page, Tab to Help, start tour, press Escape, confirm focus ring on Help button.
Reusable focus restoration module
export function createFocusGuard() {
let previousFocus = null;
return {
capture() { previousFocus = document.activeElement; },
restore() {
const target = previousFocus && previousFocus.focus ? previousFocus : document.querySelector('main, [role=main], #content')?.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
target?.focus();
}
};
}
Exception: if the tour opens from a non-focusable trigger (e.g., an automatic page-load tour), there is no previousFocus. In that case, move focus to the first heading (h1) in the main content so the user lands on meaningful content instead of the top of the page.
Result: closing the tour by any method returns keyboard focus to the element that launched it, preserving the user’s place in the page.
Related: Onboarding Tours features.
