Prevent keyboard traps in interactive components
Content available in English only.
Accessibility isn’t just about avoiding violations — it’s about ensuring that everyone can use your product with confidence. This guide explains each rule’s intent, highlights common issues, and shows how to fix them according to WCAG and the European Accessibility Act (EAA).
These guidelines do not replace the official WCAG standards. They’re concise, developer-focused notes to help you identify and fix issues effectively.
Never block Tab navigation; always provide a clean way in and out.
Why this matters and how to fix it
Why this matters
Keyboard users must be able to move focus freely throughout the interface. If focus becomes stuck inside a component and cannot be moved using Tab and Shift+Tab, users cannot continue navigating or complete tasks.
How to fix this issue
Allow focus to move both forward and backward using standard keyboard controls. Do not cancel Tab key events. For modals, set initial focus to an element inside the modal and return focus to the trigger when the modal closes.
Developer guidance
Keyboard traps are often caused by event handlers that override default keyboard behavior. Avoid blocking Tab or Shift+Tab. For modals, menus, and custom widgets, manage focus intentionally: trap focus only while the component is open and always provide an exit (Escape, close button, etc.).
Code examples
Incorrect Implementation
document.querySelector('#modal').addEventListener('keydown', e => {
if (e.key === 'Tab') e.preventDefault(); // Focus trap!
});Correct Implementation
const modal = document.querySelector('#modal');
const previouslyFocused = document.activeElement;
modal.showModal();
modal.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')?.focus();
modal.addEventListener('keydown', e => {
if (e.key === 'Escape') modal.close();
});
modal.addEventListener('close', () => previouslyFocused.focus());Real-World Examples
Before
<iframe src='widget.html'></iframe> <!-- No way to tab out of embedded widget -->After
<iframe src='widget.html' allow="keyboard-navigation"></iframe> <!-- or ensure widget allows tab to leave -->CSS Example (Guidance)
/* Visual outline for focusable elements inside modal */
.modal :focus {
outline: 2px solid #2563eb; /* Blue focus ring */
outline-offset: 2px;
}
/* Ensure hidden elements inside modal are not focusable */
.modal [aria-hidden='true'] {
pointer-events: none;
tabindex: -1;
}Manual testing
- 1. Use the keyboard only (no mouse).
- 2. Tab into the component (modal, menu, widget, iframe, custom control).
- 3. Press Tab repeatedly and check if focus can move forward to the next element.
- 4. Press Shift+Tab and check if focus can move back out to previous elements.
- 5. Confirm there is a clear way to exit (Escape or Close button).
- 6. If focus becomes stuck, a keyboard trap is present.
Trusted by organizations across Europe working toward WCAG and EAA conformance