Skip to main content
InterviewHubPRO
Section Overview
Q13

Question 13 of 50

Part 2: Core Architecture & Implementation (Mid-Level)

26%
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:

  1. 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!
  2. aria-modal="true" & role="dialog": Tells screen readers that content outside the dialog is inert.
  3. Escape Key Listener: Closes the dialog immediately.
  4. 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!
}