Sub topic 10
Making dialogs accessible
A native <dialog> opened with showModal() already does a lot of accessibility work for you. This chapter covers what the browser handles, what it leaves to you, and how to check the result. It assumes you know how to open and close a dialog, how form method="dialog" and returnValue work, and how to use autofocus.
What the browser already does
When you call showModal(), the browser does these things:
- It gives the element the implicit ARIA role
dialog. - It makes everything outside the dialog inert. Inert content can't be focused, clicked, or reached by assistive technology, so keyboard focus can't leave the dialog by tabbing.
- It moves focus into the dialog.
- It closes the dialog on Escape.
- On close, it returns focus to the element that was focused before the dialog opened.
You don't add aria-modal="true" for a showModal() dialog, and you don't write a focus trap. A library-built modal needs both, and the native element doesn't.
The browser can't supply three things: an accessible name, a sensible initial focus target, and handling for cases where the opener disappears. The rest of this chapter covers those, plus the visual side.
Give the dialog an accessible name
A screen reader announces something like "Edit profile, dialog" when focus enters. The text before "dialog" is the accessible name. Without one, users hear only "dialog" and have to explore to learn what it is.
Name the dialog with aria-labelledby, pointing at the visible heading. This keeps the name and the visible text in sync.
<dialog id="dlg" aria-labelledby="dlg-title">
<h2 id="dlg-title">Edit profile</h2>
...
</dialog>Use aria-label="Edit profile" only when no visible heading exists. Add aria-describedby when there is a short explanatory paragraph that matters for the decision, such as the consequence of a destructive action. Point it at one paragraph, not at the whole form.
| Situation | Attribute |
|---|---|
| Dialog has a visible heading | `aria-labelledby` pointing to the heading's `id` |
| No visible heading | `aria-label` with a short string |
| One key sentence explains the consequence | `aria-describedby` pointing to that paragraph |
| Dialog contains only a long form | No `aria-describedby`. Let the labels do the work. |
Choose the dialog role
A plain <dialog> is a dialog. When the dialog interrupts the user to demand a response, as in "Delete this project?", use role="alertdialog" on the same element. Screen readers announce alert dialogs more assertively, and some read the description automatically. The dialog element allows this role override.
Don't use other roles on <dialog>. Don't add tabindex to it either, because the element isn't meant to be a tab stop.
Pick the initial focus deliberately
By default the browser focuses the first focusable descendant. A descendant with the autofocus attribute takes priority. The default is often wrong, so check it.
- Form dialogs: the first input is usually right. Add
autofocusto make that explicit. - Destructive confirmations: focus Cancel, not the destructive button. A user who presses Enter by reflex then cancels instead of deleting.
- Long text, such as terms or a help article: a focused first button can scroll the content out of view, and screen reader users may miss the beginning. Give the heading
tabindex="-1"andautofocusso focus starts at the top without adding a tab stop. - Dialogs with a close button first in the DOM: put
autofocuson the main control, or the close button receives focus every time.
<dialog id="terms" aria-labelledby="terms-title">
<h2 id="terms-title" tabindex="-1" autofocus>Terms of service</h2>
<p>...long text...</p>
<form method="dialog">
<button value="decline">Decline</button>
<button value="accept">Accept</button>
</form>
</dialog>Handle focus return
The browser restores focus to the previously focused element when the dialog closes. That fails when the element is gone. A "Delete" button that removes its own row is the classic case. Focus falls back to <body>, and a keyboard user starts again from the top of the page.
When your close handler removes or hides the opener, move focus yourself to a logical place, such as a heading or the next item. Also announce the outcome through a live region. Keyboard users get no visual cue otherwise, and screen reader users may hear nothing.
This example combines the pieces so far: alertdialog, name and description, focus on Cancel, and manual focus handling after the opener is removed.
<h1 id="page-title" tabindex="-1">Project settings</h1>
<p id="status" role="status"></p>
<button id="delete-btn" type="button">Delete project</button>
<dialog id="confirm" role="alertdialog"
aria-labelledby="confirm-title"
aria-describedby="confirm-desc">
<form method="dialog">
<h2 id="confirm-title">Delete project?</h2>
<p id="confirm-desc">This permanently removes the project and its 14 files. You can't undo this.</p>
<menu>
<button value="cancel" autofocus>Cancel</button>
<button value="delete">Delete project</button>
</menu>
</form>
</dialog>
<script>
const confirmDlg = document.getElementById('confirm');
const deleteBtn = document.getElementById('delete-btn');
deleteBtn.addEventListener('click', () => {
confirmDlg.returnValue = ''; // clear the result from any earlier use
confirmDlg.showModal();
});
confirmDlg.addEventListener('close', () => {
if (confirmDlg.returnValue === 'delete') {
deleteBtn.remove();
document.getElementById('status').textContent = 'Project deleted.';
document.getElementById('page-title').focus();
}
});
</script>The returnValue = '' line matters. Pressing Escape closes the dialog without changing returnValue, so it keeps whatever the last submit set. Without the reset, a user who deletes once, reopens the dialog, and presses Escape could trigger a second "delete" in your handler.
Keyboard operation
Keyboard users need three things from a modal dialog:
- Tab and Shift+Tab cycle through controls inside the dialog. The browser handles this because the page behind is inert. Focus may reach the browser's own UI, such as the address bar, which is normal.
- Escape closes the dialog. This works for modal dialogs only. A non-modal dialog opened with
show()ignores Escape. - Every control is a real
<button>,<input>, or link, so Enter and Space work without extra code.
Always provide a visible Cancel or Close button. Don't rely on Escape alone, because some users, such as voice control users and many touch users, have no Escape key. A close button that shows only an icon needs a text alternative:
<button type="button" aria-label="Close" onclick="this.closest('dialog').close()">
<span aria-hidden="true">×</span>
</button>If you intercept the cancel event with event.preventDefault(), for example to confirm discarding unsaved changes, make sure the user still has a visible way to leave. Blocking Escape with no alternative feels like a keyboard trap.
Non-modal dialogs need more care
show() opens the dialog without inertness, without a backdrop, and without Escape handling. The page stays fully interactive, so you take on the responsibilities the browser dropped:
- Provide a close button that is easy to reach.
- Decide whether focus should move into the dialog.
show()moves it, but for a passive notification you may prefer to leave focus where it is and announce the content with a live region instead. - Place the dialog in the DOM next to related content, so the reading order makes sense.
Use a non-modal dialog for supplementary panels such as a help sidebar. For anything that requires an answer before the user continues, use showModal().
Don't use the `open` attribute to show a dialog
Setting open in markup or with dlg.setAttribute('open', '') shows the dialog as non-modal. There is no top layer, no inertness, and no focus handling. Users see something that looks like a modal, but keyboard and screen reader users can tab into the page behind it. Always open modal dialogs with showModal().
Visual accessibility
Native behavior doesn't cover how the dialog looks. Check these:
- Focus indicators. Many resets remove outlines. Keep a visible
:focus-visiblestyle on every control in the dialog, with at least 3:1 contrast against the dialog background. - Contrast. The backdrop dims the page, but the dialog's own text still needs 4.5:1 against its background.
- Zoom and small screens. At 400% zoom a tall dialog can overflow the viewport. Keep the dialog scrollable and let the content wrap.
- Reduced motion. If you animate the dialog, respect users who ask for less motion.
- Page scroll. Prevent the page behind from scrolling while the dialog is open, so touch users don't lose their place.
dialog {
max-height: 90dvh;
overflow: auto;
}
dialog :focus-visible {
outline: 3px solid #1a5fb4;
outline-offset: 2px;
}
body:has(dialog[open]) {
overflow: hidden;
}
@media (prefers-reduced-motion: reduce) {
dialog,
dialog::backdrop {
transition: none;
}
}Backdrop clicks are a bonus, not a path
Closing on a backdrop click helps mouse and touch users, but keyboard and screen reader users never use it. Treat it as an extra. Every action reachable through the backdrop must also be reachable through a visible button and through Escape. Don't make backdrop click the only way to dismiss a dialog, and avoid it for dialogs that contain unsaved input, where an accidental click loses work.
Testing checklist
Automated checkers catch a missing name but not a bad focus order. Test by hand:
| Check | What to look for |
|---|---|
| Open with the keyboard only | Focus lands on the intended control, not on `<body>` or a close icon |
| Tab through the dialog | Focus stays inside, and every control shows a visible focus ring |
| Press Escape | The dialog closes, and focus returns to the opener |
| Remove the opener in the close handler | Focus goes somewhere sensible, and the outcome is announced |
| Open with a screen reader | The announcement includes the dialog name and role |
| Reopen after closing with Escape | `returnValue` doesn't carry over a stale result |
| Zoom to 400% | Content is reachable by scrolling, and nothing is clipped |
| Enable reduced motion in your OS | Open and close transitions don't animate |
Test in at least one screen reader and browser pair you can access, such as NVDA with Firefox, VoiceOver with Safari, or TalkBack with Chrome. Native dialog support has improved, but older browser versions have had bugs in focus restoration and in announcing the name.
Common mistakes
- Using
<div role="dialog">and rebuilding focus trapping, Escape, and inertness by hand. Use<dialog>instead. - Adding
aria-modal="true"to a native modal. It is redundant. - Giving the dialog no name.
- Leaving initial focus on a destructive button.
- Forgetting to reset
returnValuebefore reopening. - Opening with the
openattribute and expecting modal behavior. - Removing the opener without moving focus.
- Hiding the only close control behind a backdrop click or Escape.
Exercise
A confirmation dialog has two buttons, "Cancel" and "Delete account", and a paragraph explaining that deletion can't be undone. Which attributes and focus choices make it accessible, and why is each needed?
Show answer
Put role="alertdialog" on the <dialog> because it demands a response. Add aria-labelledby pointing at the heading so the dialog has an accessible name, and aria-describedby pointing at the explanatory paragraph so the consequence is announced. Put autofocus on "Cancel" so that an accidental Enter press doesn't delete the account. Open it with showModal() so the page behind becomes inert and Escape works.
Exercise
A user deletes a list item with a button inside a modal flow, and your close handler removes the item's opener button from the DOM. What happens to keyboard focus, and what should your code do?
Show answer
The browser tries to return focus to the opener, but the opener no longer exists, so focus falls back to <body> and the keyboard user loses their place. In the close handler, move focus to a logical target, such as the next item, the list heading (given tabindex="-1"), or the page heading. Also write the result into a role="status" live region, such as "Item deleted", so screen reader users hear what happened.