Skip to main content

Accessibility

Implementing accessible dialogs and modals

Dialogs and modals can be useful for drawing attention to important information or actions, but they need to be implemented carefully to remain accessible and easy to use.

Modals

A modal is a dialog that opens above the page and prevents interaction with the rest of the page until it is closed. Modals can contain forms, confirmations or other content that requires the user's attention.

Prefer the native <dialog> element and open modal dialogs using showModal(). The browser will handle focus trapping, make the rest of the page inert, support closing with Escape and return focus when the dialog is closed.

Focus should move to an appropriate element inside the dialog when it opens. Always provide a visible way to close the dialog.

Alerts

Use an alert dialog for short, important messages that require an immediate response, such as confirming a destructive action.

<dialog role="alertdialog" aria-labelledby="alert-title" aria-describedby="alert-description">
<h2 id="alert-title">Are you sure?</h2>
<p id="alert-description">This action cannot be undone.</p>
<button type="button" autofocus>Cancel</button>
<button type="button">Delete</button>
</dialog>

For destructive actions, consider focusing the least destructive option by default.

Dialog

Most modal dialogs should use the native <dialog> element without an additional ARIA role.

<dialog id="modal-dialog" aria-labelledby="modal-title">
<h2 id="modal-title">Dialog title</h2>
<p>Dialog content...</p> <button type="button">Close</button>
</dialog>

Opening and closing

Open modal dialogs using showModal() rather than adding the open attribute manually.

const dialog = document.querySelector('#modal-dialog');
const openButton = document.querySelector('#open-dialog');
const closeButton = dialog.querySelector('button');
openButton.addEventListener('click', () => {
dialog.showModal();
});
closeButton.addEventListener('click', () => {
dialog.close();
});

To do

  • Use correct aria and role attributes and update when modal i opened/closed.

  • Trap tab focus on the modal when opened.

  • Modal closes with escape-button.

  • Focus modal when opened.