Focus trap

On this page 7

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.

ComponentWhat it doesTypical technique
Initial focusMoves focus into the container on openFocus the first control, the heading or the dialog itself
Boundary wrappingCycles Tab and Shift+Tab inside the containerKeydown handler or sentinel elements
Background inertingRemoves outside content from focus and the accessibility treeThe inert attribute or aria-hidden plus tabindex management
Exit mechanismLets the user leave the trap deliberatelyEscape key, close button, cancel action
Focus restorationReturns focus to the element that opened the dialogStore a reference to the trigger before opening
Core components of a modal focus trap

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.

ApproachStrengthsWeaknesses
Native dialog with showModal()Built-in inerting, Escape handling and top-layer renderingStyling quirks and fewer options for nonstandard overlays
inert on siblingsOne attribute covers focus, clicks and screen readersRequires a page structure where siblings can be targeted
Scripted keydown trapWorks with any markup and older browsersMisses virtual cursor navigation unless background is hidden
aria-modal=”true”Signals modality to screen readersDoes not move or restrict keyboard focus by itself
Ways to implement containment

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.

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.

ConceptMain purposeRelation to a focus trap
Focus managementControls where focus goes after any interface changeThe trap is a specific focus management pattern
Tab orderDefines the sequence of focusable elementsThe trap limits tab order to one container
Keyboard trap (defect)None; it is a failure conditionAn escape-less trap that violates WCAG 2.1.2
Focus indicatorShows which element has focusMust stay visible inside the trapped region
Skip linkLets users bypass repeated contentOpposite intent: it frees movement rather than restricting it
How the focus trap relates to neighboring terms

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 elementTrap focusReason
Modal dialogYesThe page behind is unavailable until the dialog closes
Full-screen mobile menuYesThe menu covers the content and acts as a modal surface
Non-modal side panelNoUsers may move between the panel and the page
Tooltip or toastNoTransient content must never capture focus
Dropdown or combobox listNoArrow keys navigate options; Tab should leave the widget
Decision guide for common overlay types

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.

SymptomLikely causeFix
Tab escapes to the pageWrapping logic misses the last or first elementUse sentinels or recompute the boundary list
Screen reader reads backgroundOutside content is not hidden from the accessibility treeApply inert or aria-hidden to siblings
Escape does nothingNo keydown listener for the Escape keyClose the dialog and restore focus on Escape
Focus lands at page top after closingTrigger reference was not savedStore the opener and call focus on it when closing
User cannot leave an embedded widgetThird-party component consumes TabProvide a documented key or replace the component
Symptoms, causes and remedies

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.