How to Build Accessible Modals and Popups
An accessible modal moves focus into the dialog when it opens, keeps keyboard focus inside while it is open, closes with Escape and a visible close button, gives the dialog a name and returns focus to the button that opened it. The easiest way to get most of this is the native HTML <dialog> element opened with showModal(). Build a custom one only if you have to.
What makes a modal accessible?
A modal dialog blocks the rest of the page until the user deals with it. For that to work for keyboard and screen reader users, five things must happen:
- Focus moves into the dialog when it opens.
- Focus stays inside while it is open, and the page behind cannot be reached.
- The dialog has a name that a screen reader announces.
- It closes with the keyboard, usually Escape plus a close button.
- Focus returns to the control that opened it.
These checks relate to 2.1.1 Keyboard, 2.1.2 No Keyboard Trap, 2.4.3 Focus Order, 4.1.2 Name, Role, Value and, for visibility, 2.4.7 Focus Visible and 2.4.11 Focus Not Obscured (Minimum). See the WCAG 2.2 AA checklist.
Should you use the native dialog element?
Yes, where you can. The <dialog> element opened with showModal() provides much of the behavior for you. According to browser behavior and the HTML specification:
- It renders in the top layer above other content.
- The rest of the page becomes inert while it is open, so users cannot tab or click behind it.
- Escape closes it.
- Focus moves into the dialog, and returns to the opener on close in current browsers.
- A
::backdroppseudo-element is available for the dimmed background.
Native dialog still needs you to add a name, a close button and sensible initial focus.
What does a native modal look like?
<button type="button" id="open-settings">Open settings</button>
<dialog id="settings" aria-labelledby="settings-title">
<h2 id="settings-title">Notification settings</h2>
<form method="dialog">
<label>
<input type="checkbox" name="email"> Email me updates
</label>
<div>
<button value="cancel">Cancel</button>
<button value="save">Save</button>
</div>
</form>
</dialog>
const dialog = document.getElementById("settings");
document.getElementById("open-settings").addEventListener("click", () => {
dialog.showModal();
});
showModal()opens it as a modal, with the page behind inert. Plainshow()opens a non-modal dialog, which does not trap focus.aria-labelledbypoints to the heading, so the dialog is announced with its name.- A form with
method="dialog"closes the dialog when a button is pressed, and returns the button'svalue.
How do you style the backdrop?
dialog::backdrop {
background: rgba(0, 0, 0, 0.6);
}
dialog {
max-width: min(32rem, 90vw);
border: 0;
border-radius: 8px;
padding: 1.5rem;
}
Keep contrast and focus styles as in the rest of your site. See focus visible and focus not obscured.
Where should initial focus go?
Focus goes to the most helpful element:
- A simple message or confirmation: the dialog's heading or the first button.
- A form: the first field.
- A destructive action such as "Delete account": the safe option, such as Cancel, not the destructive button.
- Long content: the dialog heading, so users can read from the top.
With native dialog, you can mark the element with the autofocus attribute:
<button value="cancel" autofocus>Cancel</button>
How do you handle closing?
- Escape must close the dialog, unless there is a good reason, such as unsaved work, in which case you should confirm first.
- A visible close button helps mouse, touch and screen reader users. Give it an accessible name such as "Close".
- Return focus to the opener. Native dialog does this in current browsers, but test it. If you build your own, store the opener and call
focus()on it when you close. - Do not close on a stray click if the user could lose data.
<button type="button" class="close" aria-label="Close settings">
<svg aria-hidden="true" focusable="false">...</svg>
</button>
When do you need a custom modal?
Use a custom modal when you cannot use <dialog>, such as with older browser requirements or a framework that manages the DOM itself. Then you build what the native element gave you.
<div id="modal" role="dialog" aria-modal="true" aria-labelledby="modal-title" hidden>
<h2 id="modal-title">Notification settings</h2>
<!-- content -->
<button type="button" id="modal-close">Close</button>
</div>
role="dialog"andaria-modal="true"tell assistive technology it is a modal dialog.aria-labelledbygives it a name.- Make the rest of the page inert, for example by setting the
inertattribute on the main content, or by usingaria-hiddenplus focus control. - Handle Escape yourself.
- Trap Tab and Shift+Tab inside the dialog.
- Restore focus on close.
- Stop the page behind from scrolling.
How do you trap focus in a custom modal?
const modal = document.getElementById("modal");
const focusable = 'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])';
let opener;
function openModal(trigger) {
opener = trigger;
modal.hidden = false;
document.getElementById("main").inert = true;
modal.querySelector(focusable).focus();
document.addEventListener("keydown", onKey);
}
function closeModal() {
modal.hidden = true;
document.getElementById("main").inert = false;
document.removeEventListener("keydown", onKey);
opener.focus();
}
function onKey(e) {
if (e.key === "Escape") return closeModal();
if (e.key !== "Tab") return;
const items = [...modal.querySelectorAll(focusable)];
const first = items[0];
const last = items[items.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
}
This is a simplified sketch. It assumes the modal sits outside the element with id="main". Handle dynamic content, disabled buttons and nested dialogs in production, or use a well-tested library.
Is a focus trap a keyboard trap?
A focus trap in a modal is acceptable because the user can leave it with Escape or a close button. A keyboard trap under 2.1.2 is a place where focus cannot leave. Always provide a way out.
How do you make non-modal popups accessible?
Not every pop-up is a modal.
- Cookie banners and notices. Make them reachable in a sensible order, keep them out of the way of focus, and allow dismissal by keyboard. They should not block the page unless that is truly required.
- Menus and popovers. Use a button with
aria-expanded, close on Escape and return focus to the button. HTML now has apopoverattribute for simple cases, which is supported by current browsers. Check your support needs. - Tooltips. Content shown on hover or focus must be dismissible, hoverable and persistent (1.4.13 Content on Hover or Focus).
- Toasts and alerts. Announce them with a live region, such as
role="status", instead of moving focus. See 10 ARIA mistakes.
What mistakes should you avoid?
- Opening a modal without moving focus into it.
- Leaving the background reachable by Tab or a screen reader's virtual cursor.
- No accessible name for the dialog.
- No Escape or close button.
- Failing to return focus on close.
- A close button that is only an icon with no name.
- Auto-opening modals on page load, which interrupts people (newsletter pop-ups especially).
- Stacking modals on modals.
- Not testing on mobile, where a modal can cover the page and hide its own close button.
How do you test a modal?
- Open it with the keyboard. Does focus move inside?
- Press Tab and Shift+Tab repeatedly. Does focus stay in the dialog?
- Press Escape. Does it close, and does focus return to the opener?
- Use a screen reader. Is the dialog announced with its name, and is the background hidden?
- Zoom to 200% and 400%. Can you still reach the close button?
- Test on a phone.
See the keyboard accessibility testing checklist for the full routine, and the best free accessibility testing tools for scanners.
Kerbwise audits the page you have open against WCAG 2.2 Level A and AA and ranks accessibility issues by severity, with the WCAG number, who is affected and how to fix each one. Modal behavior depends on how the page responds to keys and focus, so confirm it with the tests above.
Try Kerbwise on a page you own
Try Kerbwise ($29 one-time) to run this audit locally and export a client-ready PDF report. Get it on the Chrome Web Store or read more on the Kerbwise page.
Frequently asked questions
Should I use the native dialog element?
Yes, where browser support allows. With showModal() it makes the page behind inert, handles Escape and manages focus, so you need less code.
Is a focus trap in a modal a WCAG failure?
No. A modal needs to keep focus inside while open, as long as users can leave with Escape or a close button. A failure is when focus cannot leave at all.
Where should focus go when a modal opens?
To the first useful element, such as the dialog heading, the first field or the safest button. Use Cancel as the initial focus for destructive actions.
What should happen when the modal closes?
It should close with Escape and a close button, and focus should return to the control that opened it.
Do cookie banners need to trap focus?
Not usually. They are often non-modal. They must be keyboard accessible, dismissible and not cover the focused item.