Constrain keyboard focus within a responsive menu or dialog component
When moving keyboard focus inside a component like a responsive menu or modal, make sure that the focus doesn’t drop out of the modal when the user tabs past the last focusable element. This is called focus trapping, and unlike a keyboard trap, it gives the user a way out of the component.
When focus trapping fails, the component stays open while keyboard focus moves out of the component to the underlying content. The focus location may then be invisible or unfindable to the user.
Keep the focus while tabbing within the component:
- When focus leaves the last tabbable element in the component, move it to the first tabbable element in the component.
- Give the user a clear way out of the component. For example, a close or confirmation button and also by using the Escape key.
- Bonus functionality: the component closes when a mouse user clicks outside the component.
Tip: The HTML element <dialog> can be dismissed by pressing the Esc key by default. More info about its accessibility on MDN: dialog element.
A keyboard trap and a focus trap are two different patterns:
- Keyboard trap is a WCAG violation, the keyboard user is stuck and cannot escape.
- Focus trap is a feature, the keyboard focus is intentionally contained, but the user can always move away.
More about keyboard traps: Avoid a keyboard trap.
How to test focus trapping within a component
- Open the component.
- Tab through the component.
- Verify that the focus stays within the component, after the last focusable element the focus should return to the first focusable element in the component.
- Check if there is a close button or other way to close the component.
- Check if the component also closes with the Escape key.
Examples of focus trapping
The responsive menu on WordPress.org is an example of a component that has focus trapping.
- After tabbing through all the links, the focus returns on the close button at the top of the menu.
- The menu also closes with the Escape key.
The responsive menu with the WordPress Navigation Block handles the keyboard focus correctly. But always check the keyboard interaction yourself when installing this block on a site.
The Modal Dialog Example on ARIA Authoring Practices Guide by the W3C gives examples of an accessible dialog which uses focus trapping.
Resources
WCAG Success Criteria for keyboard focus
- 2.1.1 Keyboard (Level A).
- 2.4.3 Focus Order (Level A).
- 2.4.7 Focus Visible (Level AA).
- 2.4.11 Focus Not Obscured (Minimum) (Level AA).
- 2.4.12 Focus Not Obscured (Enhanced) (Level AAA).
Other resources
- A Primer on Focus Trapping by Zell Liew on CSS-Tricks.
- There is No Need to Trap Focus on a Dialog Element b by Zell Liew on CSS-Tricks.
- React Refocus by Mallik Cheripally.
- How to detect esc key press in React and how to handle it on XJavascript.com.
WP Accessibility Knowledge Base