Implement stackable focus traps that cycle Tab within containers
A modal dialog must keep keyboard focus inside itself: pressing Tab on the last control jumps back to the first one, and Shift+Tab on the first control jumps to the last. Real apps also open dialogs on top of dialogs (“Discard changes?” above an editor), so traps have to stack: only the top one is in charge, and closing it hands control back to the one below.
Implement createFocusTrap(container). It returns a trap object for container.
const trap = createFocusTrap(container);
trap.activate(); // start trapping focus inside container
trap.deactivate(); // stop trapping and give focus back
container (not the container itself), these elements are tabbable, in document order: a with an href, button, input, select, textarea, and any element with a tabindex attribute.<fieldset>), input type="hidden", elements with a negative tabindex, and elements that have the hidden attribute or are inside an element with it.tabindex values do not change the order; use document order.activate()document.activeElement), then focus the first tabbable element in the container, if there is one.activate() on a trap that is already active does nothing.Listen for keydown events on the document. Only the top trap reacts, and only to key === 'Tab':
preventDefault() and focus the first tabbable element.preventDefault() and focus the last tabbable element.preventDefault() and leave focus alone.preventDefault().deactivate()activate() call. The trap below it (if any) becomes the top trap again.// <button id="share">Share</button>
// <div id="dialog">
// <input aria-label="Email"> <button>Cancel</button> <button>Send</button>
// </div>
// <div id="confirm"><button>Discard</button> <button>Keep editing</button></div>
shareButton.focus();
const dialogTrap = createFocusTrap(dialog);
dialogTrap.activate(); // focus: Email
// Tab on Send -> prevented, focus: Email
// Shift+Tab on Email -> prevented, focus: Send
// Tab on Cancel -> not prevented (the browser moves to Send)
const confirmTrap = createFocusTrap(confirm);
confirmTrap.activate(); // focus: Discard; dialogTrap is paused
// Tab on Keep editing -> prevented, focus: Discard
confirmTrap.deactivate(); // focus back to Email; dialogTrap is in charge again
dialogTrap.deactivate(); // focus back to Share; Tab is no longer trapped
Tests build the markup, then dispatch keydown events (bubbles: true, cancelable: true) on the focused element and check whether the event was prevented and which element has focus. Because the test page is hidden, tests track focus through element.focus() and document.activeElement: use those, not focus events. Every test deactivates its traps at the end.