focus trap
Code that keeps keyboard focus inside a container, such as an open modal, wrapping from the last element back to the first.
In more detail
Tab on the last focusable element moves to the first, and Shift+Tab on the first moves to the last. A trap is only acceptable if Escape or a close button releases it; WCAG criterion 2.1.2 forbids traps with no way out. Traps usually also record the previously focused element so focus can be restored on close.
Examples
In the browser: Without a trap, keyboard users tab out of the dialog into the page behind it and get lost. A native dialog opened with showModal() makes the rest of the page inert, which contains focus without custom code.Most headless React dialog components also manage the trap for you.Related terms
- focus restoration — Returning keyboard focus to the element that opened an overlay, such as its trigger button, when the overlay closes.
- modal dialog — A window laid over the page that users must deal with before returning to the page beneath, with role="dialog" and aria-modal="true".
- success criterion — One numbered, testable requirement in WCAG, such as 2.1.2 No Keyboard Trap or 1.4.3 Contrast (Minimum).
- inert attribute — An HTML attribute that makes an element and everything inside it unclickable, unfocusable and hidden from assistive technology.
- custom hook — Your own function whose name starts with use and that calls other hooks, packaging stateful logic so several components can reuse it.
- dialog element — The native HTML element for dialogs; opened with showModal() it becomes an accessible modal with a backdrop and focus containment.
- tab order — The sequence in which elements receive focus when the user presses Tab (forward) or Shift+Tab (backward).
- keyboard focus — The state of being the one element on the page that receives keyboard input, usually shown with an outline.
- keyboard focus — The single element on the page that currently receives keyboard input, such as the text box you are typing into.
- keyboard navigation — Using a page entirely with the keyboard: Tab to move between controls, Enter and Space to activate, arrow keys inside widgets, Escape to close.
Taught in
- Focus Management: Trapping, Restoration & Focus Rings — Design Systems & Component Engineering
- Modal Dialogs & Alert Dialogs: Accessible Overlay Patterns — Design Systems & Component Engineering
- Pointer Events, Focus Trapping And Keyboard Accessibility — Frontend Architecture & Web Platform
- Accessible Headless Primitives: ARIA, Focus, And Keyboard — React 19 & Modern Component Architecture