Blog>
Snippets

Accessibility-Enhanced Modal

Implement an accessible modal by managing focus, adding keyboard navigation, and ARIA attributes to improve the experience for screen reader users.
<div id="modal" role="dialog" aria-modal="true" aria-labelledby="modalTitle" tabindex="-1">
  <h2 id="modalTitle">Modal Title</h2>
  <p>Some content for the modal.</p>
  <button id="closeModal">Close</button>
</div>
<button id="openModal">Open Modal</button>
HTML structure for the modal, with ARIA attributes for accessibility. The modal can be focused due to tabindex="-1" and is recognized as a dialog by screen readers because of the role attribute.
#modal {
  display: none;
  position: fixed;
  z-index: 1000;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  max-width: 400px;
  background: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

#modal[aria-modal='true'] {
  display: block;
}
CSS for the modal. Initially hidden, it becomes visible when aria-modal is true. Positioned in the center of the screen.
document.addEventListener('DOMContentLoaded', function() {
  var openButton = document.getElementById('openModal');
  var closeButton = document.getElementById('closeModal');
  var modal = document.getElementById('modal');

  function openModal() {
    modal.style.display = 'block';
    modal.setAttribute('aria-modal', 'true');
    modal.focus();
  }

  function closeModal() {
    modal.style.display = 'none';
    modal.removeAttribute('aria-modal');
    openButton.focus();
  }

  openButton.addEventListener('click', openModal);
  closeButton.addEventListener('click', closeModal);

  document.addEventListener('keydown', function(event) {
    if (event.keyCode === 27) closeModal(); // Close on Escape
  });
});
JavaScript to handle the opening and closing of the modal, manage focus to ensure keyboard navigation, and add keyboard listener for the Escape key to close the modal.