liveBook · Manning

Keyboard trap

As explained in Architecting Accessibility

A keyboard trap is a condition in which keyboard focus cannot move away from an element or component using the keyboard.

If you navigate by keyboard, getting stuck halfway through a form can mean losing your work. A keyboard trap occurs when focus reaches an element or part of a page but cannot move away using the keyboard. Someone who cannot readily switch to a mouse may have to refresh the page and start again. section 5.3.4

Focus must have a predictable way forward, backward, or out of a component such as a modal dialog or menu. Skip links help users choose where to go; they do not replace a way to leave once focus arrives. section 5.3.3

const resourceLinks = document.querySelectorAll(".resourceLink");
resourceLinks.forEach((resourceLink) => {
  resourceLink.addEventListener("keydown", (event) => { #A
    event.preventDefault(); #B
    //Some custom logic
    ...
  });
});

The keydown handler calls event.preventDefault() for every key. This is the kind of untested custom behavior that can prevent normal keyboard navigation. section 5.3.4

Try reaching each interactive component with Tab, then moving onward and back with Tab and Shift+Tab. If a component requires a special key to exit, tell users which key to press. Do not assume that activating a link successfully means keyboard users can also leave it. section 5.3.4 section 5.6

How Architecting Accessibility covers it

How deep it goes
Defines the trap, describes its impact, and shows a faulty keydown handler; the supplied example stops short of a repaired implementation.
Examples
Uses a keyboard user stuck in a pop-up or form and a resource-link handler that cancels keydown events.
What it assumes
Assumes familiarity with HTML links and JavaScript events while defining keyboard traps in plain language.
What you can do after
Diagnose/debug with it by checking whether Tab and Shift+Tab can move focus away without losing progress.
How it connects
Connects keyboard traps to focus management, sequential navigation, skip links, modal dialogs, menus, and JavaScript keyboard events.

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.