26.1. Trap focus inside a dialog
Topics
This question is in
26. AccessibilityWhen a modal dialog is open, the rest of the page is out of reach for a mouse user. A keyboard user must get the same: pressing Tab on the dialog's last button should go back to its first control, not to a link hidden behind the overlay. And when the dialog closes, focus should return to the button that opened it, so the user does not land at the top of the page. This is a focus trap.
Write trapFocus(container, options) in focus-trap.js. It returns release().
Signature
function trapFocus(container, options = {}) // returns release()container: the dialog element.options.returnFocusTo: the element to focus on release. Default:document.activeElementwhen the trap starts.
Focusable here means a Tab stop: an element sequential Tab navigation can reach, not merely one that script can focus. That is a and area with href, button, input (not type="hidden"), select, textarea, any element with a valid tabindex of 0 or more, and contenteditable elements. Leave out disabled ones (also inside a disabled fieldset), any negative tabindex (-1, -2, -01 or -1 all count: the value is read as an integer, and a negative one means focusable by script or a click but skipped by Tab), anything not drawn (hidden, display: none on it or an ancestor, visibility: hidden), and anything inside an inert element.
Requirements
- On start, focus moves to the first focusable element in the container. With none, the container gets
tabindex="-1"(if it has notabindex) and takes focus. - Tab on the last focusable element, or from the container itself, focuses the first one and calls
preventDefault(). - Shift+Tab on the first focusable element, or from the container, focuses the last one and calls
preventDefault(). - Tab and Shift+Tab between two elements inside are left to the browser: no
preventDefault, nofocus()call. - With nothing focusable, every Tab is prevented and focus stays on the container.
- The focusable elements are worked out again on every key press, so added, removed and disabled elements count.
- A Tab from outside the container brings focus back to the first element, and a Shift+Tab from outside to the last one (both call
preventDefault()). Afocusinon an element outside it brings focus back to the first element. - Keys other than Tab are not touched.
release()stops all of this, removes thetabindexit added (one the container already had stays), and focusesreturnFocusToif that element is still in the page. Calling it twice does nothing more.
Examples
openButton.addEventListener("click", () => {
dialog.hidden = false;
const release = trapFocus(dialog, { returnFocusTo: openButton });
closeButton.addEventListener("click", () => {
release(); // focus goes back to openButton
dialog.hidden = true;
}, { once: true });
});// Dialog: [Name input] [Cancel] [Save]
// Tab on Save -> Name input (prevented)
// Shift+Tab on Name -> Save (prevented)
// Tab on Name -> not prevented: the browser moves to CancelEnvironment
- Plain JavaScript in a browser page; the tests call the global
trapFocusfromfocus-trap.js. - How focus is checked: in the tests' sandboxed frame,
focus()does not move real focus anddocument.activeElementnever changes. So the tests record everyfocus()call (they wrapHTMLElement.prototype.focus), dispatch realkeydownandfocusinevents on the element that is meant to have focus, and checkdefaultPrevented. Find the focused element fromevent.target, not fromdocument.activeElement. - Out of scope: positive
tabindexvalues (their order), radio groups, nested traps, shadow DOM and iframes inside the dialog, and closing on Escape.
Hints
- Which element does the browser fire
keydownat? - If the listener is on the container, what happens to a Tab pressed while focus is somewhere else on the page?
- When
releasereturns focus to the opener, could your ownfocusinlistener get in the way?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it