Sub topic 12
Pitfalls to avoid
This chapter collects the mistakes people most often make with <dialog>. It assumes you have read the earlier chapters on showModal(), form method="dialog", returnValue, the cancel and close events, and ::backdrop styling. For each pitfall you get the symptom, the cause, and a fix.
Pitfall map
Most problems come from one of four places. The diagram shows how the open states relate, because several errors are illegal transitions between them.
Pitfall 1: Calling show methods in the wrong state
A dialog has two ways to be open, and the methods are not interchangeable.
showModal()on a dialog that is open non-modally throwsInvalidStateError.show()on a dialog that is open modally throwsInvalidStateError.showModal()on a dialog that is not in the document throwsInvalidStateError. This happens when you create the element withdocument.createElement('dialog')and forget to append it.- Older browsers also threw when
showModal()was called on a dialog that was already open modally. The current specification treats that as a no-op. Don't depend on either behavior.
A small helper makes these calls safe:
function openAsModal(dlg) {
if (!dlg.isConnected) {
document.body.append(dlg);
}
// :modal matches only dialogs opened with showModal()
if (dlg.open && !dlg.matches(':modal')) {
dlg.close();
}
if (!dlg.open) {
dlg.showModal();
}
}A related mistake is toggling the open attribute by hand, for example dlg.setAttribute('open', '') or dlg.open = true. That produces a non-modal dialog. It gets no top layer, no backdrop, no inert page, and no Escape handling. If you want a modal, call showModal(). Use dlg.close() to close, not removeAttribute('open'), so the close event and returnValue work as designed.
Pitfall 2: Overriding `display` on the dialog
A closed dialog is hidden by the browser's default style dialog:not([open]) { display: none; }. If you write your own rule like this, you break it:
/* Wrong: the dialog is now visible even when closed */
dialog {
display: flex;
flex-direction: column;
}Your author rule beats the browser's default, so every dialog on the page shows at load. The fix is to scope layout rules to the open state:
dialog[open] {
display: flex;
flex-direction: column;
}The same applies to display: grid, display: block, and anything else. If you animate with display and allow-discrete, as in the animation chapter, the same scoping rule applies.
Pitfall 3: Forms that do not close the dialog
Three form mistakes cause most "my dialog won't close" reports.
- Missing
method="dialog". Without it, the form submits like any other form. The browser navigates or reloads the page, and the dialog never gets a chance to close with a result. - Validation blocks Cancel. A Cancel button inside a form with
requiredfields tries to validate first. If a field is empty, the browser shows a validation bubble and the dialog stays open. Addformnovalidateto any button that should skip validation. - Buttons outside the form. Only a submit button inside the
<form method="dialog">(or one linked with itsformattribute) setsreturnValue. A plain<button>elsewhere in the dialog does nothing to it.
Here is a complete example that avoids all three:
<button id="open">Rename file</button>
<dialog id="rename" aria-labelledby="rename-title">
<form method="dialog">
<h2 id="rename-title">Rename file</h2>
<label>New name <input name="newName" required autofocus></label>
<button value="cancel" formnovalidate>Cancel</button>
<button value="save">Save</button>
</form>
</dialog>
<script>
const rename = document.getElementById('rename');
document.getElementById('open').addEventListener('click', () => {
rename.returnValue = ''; // see Pitfall 4
rename.showModal();
});
rename.addEventListener('close', () => {
if (rename.returnValue === 'save') {
const name = rename.querySelector('input').value;
console.log('Rename to', name);
}
});
</script>Note that the form's submit event still fires for the Save button. If you listen to it, remember that method="dialog" forms do not send data anywhere. Read the fields yourself in the close handler.
Pitfall 4: Trusting a stale `returnValue`
returnValue is a property on the dialog element, and it persists. It is not reset when the dialog opens. That causes two bugs.
- The user opens the dialog, clicks Save (
returnValueis"save"), and later opens it again and presses Escape. Thecloseevent fires andreturnValueis still"save". Your code saves something the user never confirmed. - Calling
dlg.close()with no argument leavesreturnValueas it was. Onlydlg.close('value')or a submit button'svaluechanges it.
The fix is to reset it before each opening, as the rename example does, or to set an explicit value on every close path. Escape is the path people forget. Reset to an empty string and treat anything other than your known success values as "cancelled".
Also remember that a submit button without a value attribute does not set returnValue to its label text. Give every button in a method="dialog" form an explicit value.
Pitfall 5: Mishandling Escape and `cancel`
Pressing Escape on a modal dialog fires cancel, then closes the dialog and fires close. Common errors:
- Listening for
keydownon Escape instead ofcancel. Thecancelevent also covers other close requests, such as the Android back gesture, so it is the right hook. - Calling
preventDefault()oncancelto block closing, for example to protect unsaved changes. Browsers limit this. Some ignorepreventDefault()if the user presses Escape again without interacting with the page in between, because they do not want a page to trap the user. A dialog that cannot be dismissed would break that rule. - Expecting
cancelwhen you calldlg.close()from code. It does not fire.cancelis only for user-initiated close requests.
If you must confirm before discarding, do it in the dialog. Show an "unsaved changes" message and keep Cancel and Save buttons reachable. Treat preventDefault() on cancel as a convenience, not a guarantee.
Some recent browsers also support a closedby attribute that declares how a dialog may be dismissed. Check current browser support before relying on it.
Pitfall 6: Backdrop click that closes at the wrong time
The simple backdrop handler from the earlier chapter works only when the <dialog> itself has padding: 0 and an inner wrapper carries the spacing. If the dialog has padding, clicks on that padding also have the dialog as the target, and the dialog closes when the user clicks the empty edge of their own content.
There is a second problem. A user selects text in an input, drags past the dialog edge, and releases the mouse over the backdrop. The browser fires a click on the nearest common ancestor of the press and release targets. That ancestor is the dialog, so your handler closes the dialog and the user loses their work. Track where the press started:
const dlg = document.getElementById('rename');
let pressStartedOnBackdrop = false;
dlg.addEventListener('pointerdown', (event) => {
pressStartedOnBackdrop = event.target === dlg;
});
dlg.addEventListener('click', (event) => {
if (event.target === dlg && pressStartedOnBackdrop) {
dlg.close('dismissed');
}
pressStartedOnBackdrop = false;
});Also consider whether backdrop dismissal is appropriate at all. For a form with unsaved input, closing on an accidental click is hostile. Leave the handler off for those dialogs.
Pitfall 7: Page scroll and stacking
The browser makes the rest of the page inert, but inert is not the same as scroll-locked. Depending on the browser, the page behind a modal may still scroll with the wheel or touch. Lock it with CSS:
body:has(dialog:modal) {
overflow: hidden;
}Using :modal instead of [open] means a non-modal dialog does not lock scrolling. Setting overflow: hidden can make a scrollbar disappear and shift the layout sideways. Add scrollbar-gutter: stable to html if that bothers you.
Stacking is the other trap. Top-layer elements ignore z-index against normal content, so you do not need z-index: 9999 on a dialog, and adding it does nothing. Among top-layer elements, the one added last is on top. A toast notification opened with the Popover API before your modal will therefore sit under the modal, while one opened after it will sit over it. If a dropdown or tooltip inside a modal dialog is rendered outside the dialog's DOM subtree, it is not in the top layer and will be hidden or unreachable. Keep such elements inside the dialog.
Pitfall 8: Focus surprises
The browser moves focus into a modal when it opens. It looks for an element with autofocus, and if there is none, it picks the first focusable element. That is often the Close button or a destructive action, which is a poor default.
- Put
autofocuson the safest useful control, such as the first input. For a confirmation of a delete action, put it on Cancel. - If the dialog has long text, you can put
autofocuson the dialog itself and give ittabindex="-1"so screen reader users start at the top. - When the dialog closes, focus returns to the element that was focused before opening. If you opened it from a button that you then removed from the DOM, focus falls back to
body. Move focus to a sensible element yourself in theclosehandler. - Opening a dialog from a script with no user interaction, such as on page load, has no meaningful "previous" element, so focus restoration is not useful there.
Pitfall 9: Missing accessible names and extra ARIA
A dialog needs a name, or screen reader users hear "dialog" with nothing else. Use aria-labelledby pointing at the heading, or aria-label if there is no visible title.
Don't add role="dialog" to a <dialog>, since it already has that role. Don't add aria-modal="true" to a dialog opened with showModal(). The browser already handles it. Putting role="dialog" on a <div> and calling it done skips the real behavior. Use the native element.
Don't build your own focus trap with Tab key listeners. The browser already handles it for modals, and a custom trap tends to conflict with it.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Dialog is visible when the page loads | `display` set on `dialog` | Scope the rule to `dialog[open]` |
| `InvalidStateError` on open | Wrong method for current state, or dialog not in the document | Check `open`, `:modal`, and `isConnected` first |
| Page reloads on submit | No `method="dialog"` | Add it to the form |
| Cancel button shows a validation bubble | Required fields | Add `formnovalidate` |
| `returnValue` has an old value | Not reset between openings | Reset before `showModal()` |
| Dialog closes when selecting text | Click target is the dialog after a drag | Track `pointerdown` target |
| Page behind still scrolls | Inert does not lock scrolling | `body:has(dialog:modal) { overflow: hidden; }` |
Exercises
Exercise
A dialog has padding: 1.5rem and the backdrop-click handler if (event.target === dlg) dlg.close(). Users report it closes when they click near the edge of the content. Why does this happen, and how do you fix it?
Show answer
The padding belongs to the dialog element, so a click on the padded area has the dialog as event.target, the same as a click on the backdrop. Set padding: 0 on the dialog and put the spacing on an inner wrapper such as .content. Clicks inside the wrapper then target the wrapper or its children, and only backdrop clicks target the dialog.
Exercise
A user opens a settings dialog, clicks Save, then opens it again and presses Escape. Your close handler saves the settings a second time. What is the cause, and what two changes prevent it?
Show answer
returnValue still holds "save" from the first session, because it is not reset on open and Escape does not change it. Set dlg.returnValue = '' just before each showModal(), and have the close handler act only on the exact value you expect, such as 'save'. Optionally, also give every close path an explicit value.