Skip to curriculum
Jump to the editor

26.1. Trap focus inside a dialog

Medium
Topics

This question is in

26. Accessibility
25–35 min

When 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

JAVASCRIPT
function trapFocus(container, options = {}) // returns release()
  • container: the dialog element.
  • options.returnFocusTo: the element to focus on release. Default: document.activeElement when 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

  1. On start, focus moves to the first focusable element in the container. With none, the container gets tabindex="-1" (if it has no tabindex) and takes focus.
  2. Tab on the last focusable element, or from the container itself, focuses the first one and calls preventDefault().
  3. Shift+Tab on the first focusable element, or from the container, focuses the last one and calls preventDefault().
  4. Tab and Shift+Tab between two elements inside are left to the browser: no preventDefault, no focus() call.
  5. With nothing focusable, every Tab is prevented and focus stays on the container.
  6. The focusable elements are worked out again on every key press, so added, removed and disabled elements count.
  7. 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()). A focusin on an element outside it brings focus back to the first element.
  8. Keys other than Tab are not touched.
  9. release() stops all of this, removes the tabindex it added (one the container already had stays), and focuses returnFocusTo if that element is still in the page. Calling it twice does nothing more.

Examples

JAVASCRIPT
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 });
});
JAVASCRIPT
// 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 Cancel

Environment

  • Plain JavaScript in a browser page; the tests call the global trapFocus from focus-trap.js.
  • How focus is checked: in the tests' sandboxed frame, focus() does not move real focus and document.activeElement never changes. So the tests record every focus() call (they wrap HTMLElement.prototype.focus), dispatch real keydown and focusin events on the element that is meant to have focus, and check defaultPrevented. Find the focused element from event.target, not from document.activeElement.
  • Out of scope: positive tabindex values (their order), radio groups, nested traps, shadow DOM and iframes inside the dialog, and closing on Escape.

Hints

  1. Which element does the browser fire keydown at?
  2. If the listener is on the container, what happens to a Tab pressed while focus is somewhere else on the page?
  3. When release returns focus to the opener, could your own focusin listener 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
Back to the question
Loading the editor…