Intermediate LevelHTML & Semantic Web
What is a Keyboard Trap and how do you prevent it in custom modal dialogs?
❓ Interview Prompt: Explain keyboard traps, trapping focus inside active modal dialogs, and releasing focus on Escape key.
A Keyboard Trap occurs when a keyboard user tabs into an element or modal overlay but cannot tab back out to the main page content.
Modal Focus Management Rules:
1
Trap Focus Inside Modal: When a modal opens, cycle Tab / Shift+Tab focus strictly between the modal's internal interactive elements.
2
Close on Escape: Pressing the 'Escape' key must close the modal.
3
Restore Focus: When the modal closes, explicitly return focus to the button that originally opened it!
Code Implementation Example
javascript
// Trap focus inside modal on Tab key
modal.addEventListener('keydown', (event) => {
if (event.key === 'Escape') closeModal();
if (event.key === 'Tab') {
// Focus wrapping logic between first and last focusable elements
}
});💡Managing focus cycle and Escape key listener inside modal overlays.
🎯 Interview Key Takeaway
Prevent keyboard traps by trapping focus inside open modals and returning focus to the trigger button upon closing.
#Keyboard Trap#Modal#Focus Trap#a11y#Intermediate
Back to all HTML & Semantic Web Questions→