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

Taught in

References