Web Accessibility & WCAG (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
How do you build an Accessible Modal Dialog?
senior LevelCode ExampleSystem Design
In Simple Words: An accessible modal must implement four critical requirements:
- Focus Trap: Pressing Tab on the last element inside the modal wraps focus back to the first element; pressing Shift+Tab on the first element wraps to the last. Focus must never escape to the background document!
aria-modal="true"&role="dialog": Tells screen readers that content outside the dialog is inert.EscapeKey Listener: Closes the dialog immediately.- Focus Restoration: When the modal closes, focus must return to the button that originally opened it.
javascript
let openerButton = null;
function openModal(btn) {
openerButton = btn; // Save trigger reference
modal.setAttribute('aria-hidden', 'false');
firstInput.focus();
document.addEventListener('keydown', trapFocus);
}
function closeModal() {
modal.setAttribute('aria-hidden', 'true');
document.removeEventListener('keydown', trapFocus);
openerButton?.focus(); // Restore focus!
}