How to Build an Accessible Modal Dialog, with Code to Copy
What a dialog has to do when it opens, while it is open and when it closes, with the WCAG criterion behind each requirement.
Like accessible custom dropdowns, modals are everywhere. Cookie consent, login forms, confirmation dialogs, image lightboxes, newsletter signups, settings panels. On a lot of commercial sites you meet one before you have read a line of the page. And a modal built for mouse users alone is broken for everyone else.
A modal fails in ways the rest of a page does not, because it has to take over the keyboard, announce itself to assistive technology, and hand focus back when it closes. This post works through the three requirements that carry most of that weight: focus management, a keyboard route out, and telling screen readers the dialog opened. To see where a client's dialogs stand, run a free accessibility scan of a page that opens one, then do the keyboard pass below by hand. Automated checks find many problems but cannot confirm conformance, and a modal needs a human at the keyboard.
Below: the WCAG criteria behind each requirement, what the native <dialog> element does for you, and three complete accessible modal dialog examples you can copy, then test with the keyboard pass at the end.
Why modals are uniquely dangerous for accessibility
A modal dialog does something no other UI pattern does: it demands exclusive attention. It sits on top of everything, it (should) prevent interaction with the page behind it, and it expects the user to deal with it before doing anything else.
For sighted mouse users, that contract is visually obvious. The backdrop dims, the box appears in the center, you click inside it or click the X to close it. Done.
For everyone else, the contract is invisible unless you build it explicitly. A screen reader user has no idea a modal just appeared unless you tell their assistive technology. A keyboard user cannot "see" the backdrop and will tab straight out of the modal into the page behind it unless you trap focus. A voice control user cannot say "click close" unless the close button has an accessible name.
The result is that a modal either works perfectly or fails catastrophically. There is no graceful degradation. A half-accessible modal is arguably worse than a completely inaccessible one, because it lets users get halfway in before stranding them.
The WCAG criteria that apply to modals
Modals touch a surprisingly large number of WCAG success criteria. Here are the ones that matter most, in the order you are most likely to fail them. Every number, title and level below is from WCAG 2.2.
4.1.2 Name, Role, Value (Level A). The modal must have role="dialog" or role="alertdialog", and it must have an accessible name via aria-labelledby or aria-label. Without these, screen readers do not announce it as a dialog. They treat it as a random pile of HTML that appeared on the page.
2.4.3 Focus Order (Level A). When the modal opens, focus moves into it, and when it closes, focus goes back to where the user was. The Understanding document for 2.4.3 uses this exact case as its example: focus is set within the dialog when it opens, and "when the dialog is dismissed, focus returns to the button or the element following the button." If focus stays on the page behind the modal, keyboard users are interacting with content they cannot see.
2.1.2 No Keyboard Trap (Level A). The user must be able to leave the modal using the keyboard. The criterion names no particular key, and its Understanding document allows focus to be held inside a modal dialog as long as the user can get out. A close button that works from the keyboard satisfies it. Escape is what people expect, and the WAI-ARIA dialog pattern lists it as the key that closes the dialog, so provide it as well. A modal with no focusable element and no Escape handler is a real trap.
2.1.1 Keyboard (Level A). Every interactive element inside the modal must be operable with a keyboard. This sounds obvious, but custom close buttons built from div elements with only an onclick handler fail this completely.
1.3.1 Info and Relationships (Level A). The modal's heading, form labels, and structure must be conveyed programmatically. A modal whose title is a styled span rather than a heading gives screen reader users nothing to jump to and nothing for aria-labelledby to point at in good faith.
2.4.7 Focus Visible (Level AA). Focus indicators must be visible inside the modal, just like everywhere else, and our keyboard and focus checker flags the pages where they are suppressed. Many modal libraries apply outline: none to their containers for cosmetic reasons, which kills focus visibility for every element inside.
1.4.3 Contrast (Level AA). The modal's text, buttons, and links need to meet the same 4.5:1 contrast ratios as the rest of the page. The semi-transparent backdrop behind the modal does not count as the background color for contrast calculations. The modal's own background does.
Use the native dialog element
The single biggest improvement you can make is to use the HTML <dialog> element instead of building a modal from divs. The <dialog> element, when opened with its .showModal() method, gives you several things for free that would otherwise take dozens of lines of JavaScript to replicate.
It creates a top layer that sits above everything else in the document, no z-index wars. It renders a backdrop you can style with the ::backdrop pseudo-element. It makes the rest of the document inert, so Tab cannot reach the page behind the dialog. It closes on Escape by default. And the HTML standard has the browser return focus to the element that was focused before a modal dialog opened.
Here is the minimal accessible pattern:
<button id="open-btn" onclick="document.getElementById('my-dialog').showModal()">
Open settings
</button>
<dialog id="my-dialog" aria-labelledby="dialog-title">
<h2 id="dialog-title">Settings</h2>
<p>Adjust your notification preferences below.</p>
<form method="dialog">
<label for="email-notifications">
<input type="checkbox" id="email-notifications" checked>
Email notifications
</label>
<button type="submit">Save</button>
</form>
</dialog>
That is it. No ARIA role needed because <dialog> has an implicit role of dialog. No JavaScript focus trap because .showModal() makes the page behind it inert. No Escape key handler because the browser does it. The browser also puts focus back when the dialog closes, though example 1 below sets it explicitly as well, which costs one line and guards against an older browser. The method="dialog" on the form means submitting it closes the dialog, which is the correct behavior for settings panels and confirmation dialogs.
MDN lists <dialog> as Baseline widely available, working across browsers since March 2022, so browser support is no longer a reason to avoid it.
If you cannot use dialog: the manual checklist
Sometimes you are working with a legacy codebase, a component library that predates native dialog support, or a framework that generates its own modal markup. In those cases, you need to build every feature by hand. Here is the complete list.
1. Add role="dialog" and an accessible name.
<div role="dialog" aria-labelledby="modal-heading" aria-modal="true">
<h2 id="modal-heading">Confirm deletion</h2>
<!-- modal content -->
</div>
The aria-modal="true" attribute tells assistive technology that the rest of the page is inert. This is the ARIA equivalent of what .showModal() does natively. Without it, screen readers may let users navigate to content behind the modal using virtual cursor commands, even if you have a visual backdrop.
2. Move focus into the modal on open. Focus should land on the first focusable element inside the modal, or on the modal container itself if it has tabindex="-1". Never leave focus on the trigger button behind the backdrop.
function openModal(modal) {
modal.style.display = 'flex';
const firstFocusable = modal.querySelector(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
if (firstFocusable) {
firstFocusable.focus();
} else {
modal.setAttribute('tabindex', '-1');
modal.focus();
}
}
3. Trap focus inside the modal. Tab and Shift+Tab must cycle through the modal's focusable elements without ever leaving. When the user tabs past the last element, focus wraps to the first. When they shift-tab before the first, focus wraps to the last.
function trapFocus(modal, event) {
const focusables = modal.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
const first = focusables[0];
const last = focusables[focusables.length - 1];
if (event.key === 'Tab') {
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
}
4. Close on Escape. Users expect Escape to close a modal, and the native element does it for free, so a hand-built one should too.
modal.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
closeModal(modal);
}
});
5. Return focus on close. When the modal closes, focus must return to the element that opened it. If that element no longer exists (it was removed from the DOM while the modal was open), focus should go to a sensible fallback, like the main content area.
let triggerElement = null;
function openModal(modal, trigger) {
triggerElement = trigger;
modal.style.display = 'flex';
// ... focus first element
}
function closeModal(modal) {
modal.style.display = 'none';
if (triggerElement && document.body.contains(triggerElement)) {
triggerElement.focus();
} else {
document.querySelector('main')?.focus();
}
}
6. Make the backdrop inert. While the modal is open, users should not be able to interact with anything behind it. For screen readers, aria-modal="true" handles this. For keyboard users, the focus trap handles it. For mouse users, the backdrop click handler handles it. But for completeness, consider adding the inert attribute to the rest of the page content:
document.querySelector('main').setAttribute('inert', '');
// Remove it when the modal closes
document.querySelector('main').removeAttribute('inert');
The inert attribute makes an element and all its descendants unfocusable and invisible to assistive technology. It is the nuclear option and it works. MDN lists inert as Baseline widely available, across browsers since April 2023.
The close button problem
Almost every modal has an X button in the top-right corner. Almost every one of them is broken. Here is why, and how to fix it.
The most common pattern we see in the wild:
<!-- broken -->
<div class="close-btn" onclick="closeModal()">×</div>
This fails two criteria at once. It is not a button, so it is not keyboard focusable and cannot be operated without a mouse (fails 2.1.1). It has no role and no useful name, because the multiplication sign is a symbol, not the word "close" (fails 4.1.2).
The fix:
<!-- fixed -->
<button type="button" aria-label="Close" onclick="closeModal()">
<svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24">
<path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2"/>
</svg>
</button>
Use a real <button>. Give it aria-label="Close" so screen readers announce "Close, button." Hide the decorative SVG icon from assistive technology with aria-hidden="true". Done.
Alert dialogs: when the modal demands a decision
If your modal requires the user to acknowledge something or make a choice before proceeding (confirm deletion, accept terms, session timeout warning), use role="alertdialog" instead of role="dialog".
<dialog role="alertdialog" aria-labelledby="alert-title" aria-describedby="alert-desc">
<h2 id="alert-title">Delete this project?</h2>
<p id="alert-desc">This will permanently remove the project and all its data. This action cannot be undone.</p>
<button onclick="confirmDelete()">Delete permanently</button>
<button onclick="this.closest('dialog').close()">Cancel</button>
</dialog>
The difference is that alertdialog marks the dialog as one that diverts attention to a brief, important message, which is how the WAI-ARIA alert dialog pattern describes it, and it lets browsers and assistive technology give it special treatment, such as playing a system alert sound. Use this for destructive actions, timeouts, and errors. Do not use it for settings panels, forms, or informational content, that is what regular dialog is for.
Notice the aria-describedby pointing to the explanatory paragraph. This gives screen readers the full context: "Delete this project? dialog. This will permanently remove the project and all its data." Without it, they only hear the title, which may not convey the severity.
If your modal comes from a library
Most sites do not hand-build their dialogs. They come from Bootstrap, a React component library, a page builder or a plugin, and those vary in how much of the work above they do. Rather than trust a library's reputation, test what it renders on your page, because the usual breakages are made by the site, not the library:
-
The close button lost its name. The library ships
aria-label="Close"and a template override swapped the button for an icon with no text. - The title was left out. Many libraries name the dialog from a title prop or a heading slot. Skip it and the dialog is announced as "dialog" and nothing else.
- Keyboard handling was switched off. An option such as disabling Escape or backdrop close, set for a design reason, removes the expected way out.
- A second focus trap fights the first. A cookie banner or chat widget opened on top of a library modal, each trying to hold focus.
The keyboard test further down catches all four in two minutes, whatever built the dialog.
Three dialogs you can copy
Everything above is the reasoning. This section is the code. Each of the three is complete: paste it into a page and it works, with no library and nothing left as an exercise.
1. The modal dialog, native
This is the one to reach for. showModal() gives you the focus trap, the Escape key, the backdrop and the inert background for free, so the only line left to write makes sure focus returns to the trigger.
<button type="button" id="open-settings">Settings</button>
<dialog id="settings-dialog" aria-labelledby="settings-title">
<h2 id="settings-title">Settings</h2>
<p>Choose how often we email you.</p>
<form method="dialog">
<label for="frequency">Frequency</label>
<select id="frequency" name="frequency">
<option>Daily</option>
<option>Weekly</option>
</select>
<button value="cancel">Cancel</button>
<button value="save">Save</button>
</form>
</dialog>
const dialog = document.getElementById('settings-dialog');
const openButton = document.getElementById('open-settings');
openButton.addEventListener('click', () => dialog.showModal());
// Browsers following the HTML standard restore focus themselves; this makes sure of it.
dialog.addEventListener('close', () => openButton.focus());
/* The backdrop is a real pseudo-element, so style it here, not with a div */
#settings-dialog::backdrop {
background: rgb(0 0 0 / 0.5);
}
Two notes. showModal() is what makes it modal; show() and open do not trap focus or block the page. And <form method="dialog"> closes the dialog on submit and puts the pressed button's value into dialog.returnValue, so a cancel button needs no JavaScript at all.
2. The non-modal dialog
A non-modal dialog sits on the page without taking it over: a filter panel, a notification, a small editor beside the thing it edits. The rules are different and people get them backwards. A non-modal dialog must not trap focus and must not carry aria-modal="true", because the rest of the page is still available and saying otherwise lies to a screen reader.
<button type="button" id="open-filters" aria-expanded="false">Filters</button>
<div id="filters" role="dialog" aria-labelledby="filters-title" hidden>
<h2 id="filters-title">Filter results</h2>
<label><input type="checkbox" name="open"> Open issues only</label>
<button type="button" data-close>Done</button>
</div>
const panel = document.getElementById('filters');
const toggle = document.getElementById('open-filters');
function openPanel() {
panel.hidden = false;
toggle.setAttribute('aria-expanded', 'true');
panel.querySelector('input, button').focus(); // move focus in, do not trap it
}
function closePanel({ returnFocus = true } = {}) {
panel.hidden = true;
toggle.setAttribute('aria-expanded', 'false');
if (returnFocus) toggle.focus();
}
toggle.addEventListener('click', () => panel.hidden ? openPanel() : closePanel());
panel.querySelector('[data-close]').addEventListener('click', () => closePanel());
// Escape closes it, the same as a modal
panel.addEventListener('keydown', (event) => {
if (event.key === 'Escape') closePanel();
});
// Tabbing out of it is allowed, and closes it without stealing focus back
panel.addEventListener('focusout', (event) => {
if (!panel.contains(event.relatedTarget)) closePanel({ returnFocus: false });
});
The returnFocus flag is the detail that makes this behave. On Escape and on the Done button, focus goes back to the trigger. When somebody simply tabs past the panel, it closes and lets them carry on, because pulling focus back to the trigger there would be a focus trap wearing a different hat.
One criterion applies to non-modal dialogs and not to modal ones: because the page behind it still scrolls, a non-modal dialog can end up covering the element that has focus, which fails 2.4.11 Focus Not Obscured (Minimum), Level AA. W3C names "non-modal dialogs" among the usual causes, alongside sticky headers and footers (Understanding SC 2.4.11).
3. The modal fallback, without the dialog element
Use this only when a design system or an old browser target rules out <dialog>. It is four separate jobs the browser was doing for you, and each one is a place to get it wrong.
<button type="button" id="open-confirm">Delete project</button>
<div id="confirm-backdrop" class="backdrop" hidden>
<div id="confirm" role="dialog" aria-modal="true" aria-labelledby="confirm-title">
<h2 id="confirm-title">Delete this project?</h2>
<p>This cannot be undone.</p>
<button type="button" data-cancel>Cancel</button>
<button type="button" data-confirm>Delete</button>
</div>
</div>
const backdrop = document.getElementById('confirm-backdrop');
const modal = document.getElementById('confirm');
const main = document.querySelector('main');
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), ' +
'select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
let lastTrigger = null;
function openModal(trigger) {
lastTrigger = trigger;
backdrop.hidden = false;
main.setAttribute('inert', ''); // 1. background out of reach
modal.querySelector(FOCUSABLE).focus(); // 2. focus moves in
document.addEventListener('keydown', onKeydown);
}
function closeModal() {
document.removeEventListener('keydown', onKeydown);
backdrop.hidden = true;
main.removeAttribute('inert');
if (lastTrigger) lastTrigger.focus(); // 3. focus goes back
}
function onKeydown(event) {
if (event.key === 'Escape') return closeModal();
if (event.key !== 'Tab') return;
// 4. the focus trap: wrap at both ends
const items = [...modal.querySelectorAll(FOCUSABLE)];
if (items.length === 0) return;
const first = items[0];
const last = items[items.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
document.getElementById('open-confirm')
.addEventListener('click', (event) => openModal(event.currentTarget));
modal.querySelector('[data-cancel]').addEventListener('click', closeModal);
backdrop.addEventListener('click', (event) => {
if (event.target === backdrop) closeModal(); // backdrop click, not content click
});
Compare that with the few lines in example 1 and you have the argument for using the native element, in a form you can show a client or a sceptical lead developer.
Testing your modals
You can test modal accessibility in under five minutes with nothing but your keyboard and a screen reader. Here is the exact process, and our step by step guide to testing keyboard accessibility by hand puts it in the context of a full page pass.
Keyboard test (two minutes). Open the modal using only the keyboard (Tab to the trigger, press Enter). Verify that focus moves into the modal. Press Tab repeatedly and confirm focus cycles through all interactive elements inside the modal and never leaves it. Press Shift+Tab from the first element and confirm focus wraps to the last element. Press Escape and confirm the modal closes. Confirm focus returns to the trigger button.
Screen reader test (three minutes). Turn on VoiceOver (Cmd+F5 on Mac) or NVDA (free on Windows). Open the modal. Listen for the screen reader to announce the dialog role and its name (e.g., "Settings, dialog"). Navigate through the content and confirm everything is announced. Close the modal and confirm the screen reader announces the return to the trigger button.
A dialog that does not take focus, cannot be left from the keyboard, or is announced with no name fails WCAG. One that does not wrap focus on Shift+Tab or ignores Escape breaks what users expect and what the WAI-ARIA pattern asks for, so fix it too, but describe it to a client as a usability failure rather than a WCAG one.
What AccessGuard checks automatically
Our scanner runs in a real browser and flags the static half of this guide on every page you scan: a visible element with role="dialog", role="alertdialog" or a <dialog> that has no accessible name (4.1.2); click handlers on elements such as a div close button that cannot be reached from the keyboard (2.1.1); and focus outlines removed with no replacement (2.4.7).
It does not open and close your dialogs, so it cannot test whether focus moves in, stays in, or comes back. That half is the keyboard test above. Our ARIA checker covers the role and naming half, and the keyboard and focus checker covers the keyboard half, across every page you add.
Worth saying plainly to clients: automated checks find many real problems, but no scan can confirm that a dialog conforms to WCAG. A modal passes or fails on what happens when somebody opens it, and that needs a person. Run a free accessibility scan for the static half, then test the behaviour by hand.
The one-paragraph summary
Use the native <dialog> element with .showModal(). Give it an accessible name with aria-labelledby. Make sure the close button is a real <button> with aria-label="Close". If you cannot use native dialog, add role="dialog", aria-modal="true", trap focus manually, close on Escape, and return focus on close. Test it with your keyboard. Test it with a screen reader. That is the whole thing.