A focus trap is a scripted behavior that confines keyboard focus to a bounded region of a page, typically a modal dialog, so that pressing Tab or Shift+Tab cycles only through the controls inside that region until it is dismissed. In web accessibility, the term has two faces: an intentional focus trap is a required pattern for modal interfaces, while an unintentional keyboard trap is a serious defect that leaves keyboard users stranded.
The distinction matters because WCAG 2.2 Success Criterion 2.1.2, No Keyboard Trap, forbids components that capture focus without a documented way out. A correct modal focus trap satisfies that criterion because it always offers an exit, usually the Escape key and a visible close button, and it returns focus to the triggering element when the dialog closes.
How a focus trap contains keyboard navigation
A focus trap works by intercepting focus movement at the boundaries of a container. When the user presses Tab on the last focusable element, the script moves focus to the first one; when the user presses Shift+Tab on the first element, focus wraps to the last. The rest of the page remains visible but becomes unreachable by keyboard while the trap is active.
Implementations rely on a few cooperating parts. The script must compute the list of focusable elements inside the container, listen for keyboard and focus events, and restore the previous state when the trap is released. The table below summarizes those components and what each one contributes.
| Component | What it does | Typical technique |
|---|---|---|
| Initial focus | Moves focus into the container on open | Focus the first control, the heading or the dialog itself |
| Boundary wrapping | Cycles Tab and Shift+Tab inside the container | Keydown handler or sentinel elements |
| Background inerting | Removes outside content from focus and the accessibility tree | The inert attribute or aria-hidden plus tabindex management |
| Exit mechanism | Lets the user leave the trap deliberately | Escape key, close button, cancel action |
| Focus restoration | Returns focus to the element that opened the dialog | Store a reference to the trigger before opening |
Two wrapping strategies are common. A keydown handler inspects Tab presses and redirects focus at the edges, while sentinel elements are invisible focusable nodes placed before and after the container that bounce focus back inside when reached. Sentinels also catch focus that arrives by other means, such as programmatic calls from third-party scripts.
Native dialog, inert and scripted approaches
Modern browsers reduce the amount of custom code needed. The HTML dialog element opened with showModal() makes the rest of the document inert by default, places the dialog in the top layer and closes on Escape. The `inert` attribute can also be applied to sibling regions, which removes them from tab order, pointer interaction and the accessibility tree in one step.
The approaches differ in browser support, effort and the behavior of assistive technology. The following comparison shows when each option is appropriate.
| Approach | Strengths | Weaknesses |
|---|---|---|
| Native dialog with showModal() | Built-in inerting, Escape handling and top-layer rendering | Styling quirks and fewer options for nonstandard overlays |
| inert on siblings | One attribute covers focus, clicks and screen readers | Requires a page structure where siblings can be targeted |
| Scripted keydown trap | Works with any markup and older browsers | Misses virtual cursor navigation unless background is hidden |
| aria-modal=”true” | Signals modality to screen readers | Does not move or restrict keyboard focus by itself |
A frequent misconception is that aria-modal alone creates a focus trap. The attribute only informs assistive technology that content outside the dialog is unavailable; support varies between screen readers, and it never stops the Tab key. Robust implementations combine semantic signals with actual containment.
Focus trap compared with related accessibility concepts
A focus trap is one technique within the broader discipline of focus management, which covers every deliberate movement of focus in an application. It also interacts with tab order, focus indicators and skip links, each of which has its own page and purpose.
| Concept | Main purpose | Relation to a focus trap |
|---|---|---|
| Focus management | Controls where focus goes after any interface change | The trap is a specific focus management pattern |
| Tab order | Defines the sequence of focusable elements | The trap limits tab order to one container |
| Keyboard trap (defect) | None; it is a failure condition | An escape-less trap that violates WCAG 2.1.2 |
| Focus indicator | Shows which element has focus | Must stay visible inside the trapped region |
| Skip link | Lets users bypass repeated content | Opposite intent: it frees movement rather than restricting it |
The key difference between a pattern and a defect is user control. A dialog trap is announced, bounded and escapable; a defective trap appears when an embedded media player, map widget or rich text editor swallows Tab presses and offers no keyboard path back to the page.
When to use a focus trap and how to configure it
A focus trap is appropriate when an overlay blocks interaction with the underlying page. If users can still meaningfully work with the content behind a panel, trapping focus is the wrong choice and creates friction instead of clarity.
| Interface element | Trap focus | Reason |
|---|---|---|
| Modal dialog | Yes | The page behind is unavailable until the dialog closes |
| Full-screen mobile menu | Yes | The menu covers the content and acts as a modal surface |
| Non-modal side panel | No | Users may move between the panel and the page |
| Tooltip or toast | No | Transient content must never capture focus |
| Dropdown or combobox list | No | Arrow keys navigate options; Tab should leave the widget |
Configuration details decide whether the trap feels natural. Initial focus placement should follow the content: a confirmation dialog can focus the least destructive button, while a long form dialog usually focuses its heading or first field. The dialog needs an accessible name through aria-labelledby, and the trigger reference must be stored before opening so that focus returns predictably on close.
- Recalculate focusable elements when dialog content changes dynamically.
- Exclude elements that are hidden, disabled or have a negative tabindex.
- Prevent background scrolling so that sighted keyboard users keep context.
- Support nested dialogs by stacking traps and releasing them in reverse order.
Common focus trap failures and their fixes
Most problems come from incomplete implementations rather than from the concept itself. Testing with a keyboard and at least one screen reader reveals them quickly, because each failure produces a recognizable symptom.
| Symptom | Likely cause | Fix |
|---|---|---|
| Tab escapes to the page | Wrapping logic misses the last or first element | Use sentinels or recompute the boundary list |
| Screen reader reads background | Outside content is not hidden from the accessibility tree | Apply inert or aria-hidden to siblings |
| Escape does nothing | No keydown listener for the Escape key | Close the dialog and restore focus on Escape |
| Focus lands at page top after closing | Trigger reference was not saved | Store the opener and call focus on it when closing |
| User cannot leave an embedded widget | Third-party component consumes Tab | Provide a documented key or replace the component |
Another subtle failure involves focus on removed elements: if the control holding focus is deleted while the dialog updates, browsers move focus to the document body and the trap silently breaks. Robust code moves focus before removing content and keeps the boundary list synchronized with the DOM.
In plain words
Many people move through websites with the keyboard instead of a mouse, pressing Tab to jump from one button or link to the next. When a pop-up window opens, a focus trap keeps that jumping inside the pop-up, so the person does not wander into the page hidden behind it.
Think of it as a room with one clearly marked door. While you are inside, walking around only takes you past the things in that room. The door, usually the Escape key or a close button, always lets you out, and when you leave you are back exactly where you started. A bad trap is a room with no door, and that is a real barrier for keyboard users.
A real-world example
A regional bank redesigns its online banking portal and adds a dialog that asks customers to confirm a transfer. During an accessibility audit, a tester using only a keyboard finds that pressing Tab after the Confirm button moves focus into the account list behind the overlay, where a second Tab press can start another transfer. A screen reader user hears the background transaction history read aloud while the dialog is open.
The front-end team rebuilds the confirmation with the native dialog element opened through showModal(), adds an accessible name taken from the dialog heading and sets initial focus on the Cancel button to reduce accidental confirmations. On close, focus returns to the Transfer button that opened the dialog. A follow-up test with NVDA, VoiceOver and keyboard-only navigation confirms that focus stays inside the dialog, Escape closes it, and the audit finding is resolved before release.