liveBook · Manning

Focus trapping

As explained in Architecting Accessibility

A focus trap is a technique that intentionally confines keyboard focus within an active interface component.

A focus trap keeps keyboard focus inside an open modal so users cannot interact with background content. It becomes a keyboard trap when users cannot dismiss the modal and return focus to its trigger. Provide a reliable exit, such as Escape or a Close button, so users can move on. section 5.3.4

Check that keyboard users can navigate into and out of interactive elements:

  • Press Tab repeatedly through the page, then use Shift+Tab to navigate back. Check that focus can move past custom components such as dropdowns and date pickers. section 5.3.4
const resourceLinks = document.querySelectorAll(".resourceLink");
resourceLinks.forEach((resourceLink) => {
  resourceLink.addEventListener("keydown", (event) => { #A
    event.preventDefault(); #B
    //Some custom logic
    ...
  });
});

This keydown handler calls preventDefault() before custom logic, a pattern that can interfere with default keyboard behavior. section 5.3.4

How Architecting Accessibility covers it

How deep it goes
Explains how missing dismissal and focus return turn intended containment into a keyboard trap, and gives navigation tests.
Examples
Uses modal dialogs, dropdowns, date pickers, and a keydown handler that prevents default behavior.
What you can do after
Diagnose keyboard traps by tabbing through interactive elements and checking reverse navigation with Shift+Tab.
How it connects
Connects focus trapping with modal dialogs, keyboard traps, and custom components.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Architecting Accessibility. The section links point to the parts of the book it draws on.