tezvyn:

Focus Trapping: Guiding Keyboard Users, Not Caging Them

AI-drafted, machine-checkedSource: w3.orgadvanced

Focus trapping intentionally confines keyboard navigation to a component, like a modal. It's a feature, not a bug, when used to prevent users from interacting with the page behind an overlay.

WHY IT EXISTS Focus trapping solves the problem of keyboard focus leaking out of temporary UI contexts. When a modal dialog appears, a keyboard user shouldn't be able to tab to the main page content underneath it. This would be confusing and break the intended workflow, violating accessibility principles.

THE MENTAL MODEL Think of focus trapping like putting up temporary velvet ropes at an event. You're intentionally guiding guests (the user's focus) within a specific area (a modal dialog) and preventing them from wandering into restricted zones (the underlying page). The ropes must have a clear exit point, like the Esc key or a close button.

HOW IT WORKS When a component like a modal is activated, JavaScript listens for keyboard events. When the user presses Tab on the last focusable element, the script programmatically moves focus back to the first focusable element. Pressing Shift+Tab on the first element moves focus to the last. This creates a "focus cycle" or "focus jail." A separate event listener for the Esc key or a click on a close button will dismantle the trap and return focus to the element that originally opened the modal.

WHEN TO USE IT Use intentional focus trapping for any UI that overlays the main page and demands the user's full attention. This includes modal dialogs, lightboxes, and some complex popovers. The goal is to create a temporary, contained navigation scope so the user can only interact with the foreground component.

WHEN NOT TO USE IT Never implement an unintentional focus trap. This is a critical accessibility failure (WCAG 2.1.2). If a user can tab into a custom widget, they must be able to tab out using standard methods (Tab, Shift+Tab, arrows). If a component must repurpose standard keys, like a rich text editor using Tab for indentation, you must provide clear, visible instructions on the alternative method for exiting the component (e.g., "Press Alt+F10 to exit").

ONE CANONICAL EXAMPLE A modal dialog for confirming an action. When it opens, focus is immediately moved inside it. The user can tab between the "Confirm" and "Cancel" buttons, but they cannot tab to the main page behind the modal. Pressing Esc or activating the "Cancel" button closes the dialog and returns focus to the element that opened it. This is a perfect, user-friendly implementation of focus trapping.

Read the original → w3.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.