Dialog in Practice
The earlier lesson on the Dialog element showed you how to open and close one, how method="dialog" works, and how to style the backdrop. This lesson picks up from there. It is about what happens when you build real dialogs: forms that must be checked before they close, different ways to dismiss them, focus, scrolling, animation, and the question of when not to use a dialog.
What You Will Learnβ
- What the "top layer" is, and why
z-indexdoes not matter - How to check a form inside a dialog before it closes
- The ways a dialog can be dismissed, and how to control them
- What happens to focus, and how to protect the page behind
- How to add an optional, gentle animation
- How to choose between a dialog, a popover, and details
The Big Ideaβ
A dialog is a small state machine: it is closed, or open as modal, or open as non-modal, and it ends with a returnValue. Everything in this lesson is a way of hooking into those moments: before it closes, while it is open, and after it closes.
- Rename Dialog Lab
- Which One Fits?
- The Code
Current file name: report.txt
Event log (newest first)
Open the dialog and try: an empty name, a name with a slash, Escape, a click outside, Cancel, and Save.This is a real dialog element. The checkbox adds the click-outside rule with a few lines of script. Nothing you type is stored or sent anywhere.
Scenario 1 of 6: Confirm deleting an account. Nothing else on the page should work until the visitor answers.
<button type="button" id="rename">Rename</button>
<dialog id="rename-dialog" aria-labelledby="rename-title">
<form method="dialog">
<h2 id="rename-title">Rename file</h2>
<label for="name">New name</label>
<input id="name" name="name" type="text">
<p id="name-error" role="alert"></p>
<button value="cancel" formnovalidate>Cancel</button>
<button value="save">Save</button>
</form>
</dialog>
const dialog = document.getElementById("rename-dialog");
const form = dialog.querySelector("form");
const error = document.getElementById("name-error");
document.getElementById("rename").addEventListener("click", () => {
error.textContent = "";
dialog.showModal();
});
// Check the value BEFORE the dialog closes
form.addEventListener("submit", (event) => {
if (event.submitter && event.submitter.value === "cancel") return;
const value = form.elements.name.value.trim();
if (value === "") {
event.preventDefault(); // keeps the dialog open
error.textContent = "Enter a file name.";
}
});
// After it closes, read what happened
dialog.addEventListener("close", () => {
if (dialog.returnValue === "save") {
console.log("New name:", form.elements.name.value.trim());
}
});
// Optional: click outside to close
dialog.addEventListener("click", (event) => {
if (event.target === dialog) dialog.close("dismissed");
});
The Top Layerβ
A modal dialog does not live in the normal stacking order of your page. It is placed in the browser's top layer, a special layer above everything else. That is why:
- you never need a huge
z-indexto bring a dialog to the front, and az-indexon other elements cannot cover it, - the dialog is not clipped by a parent with
overflow: hidden, - if you open a dialog from inside another dialog, the newer one is on top.
You can ask whether a dialog is currently modal with dialog.matches(":modal"), and style it with the :modal pseudo-class. The lab above logs this when you open it.
Pattern 1: Check a Form Before It Closesβ
A form with method="dialog" closes the dialog on submit, so a mistake would close the dialog and throw away the visitor's work. To keep it open while there is a problem:
- Listen for
submiton the form, not for clicks on the Save button. Submit also fires when the visitor presses Enter. - Check
event.submitter. The Cancel button should always close, so let it through. - Call
event.preventDefault()when the value is not good. The dialog stays open. - Show the error inside the dialog, in an element with
role="alert", and connect it to the field witharia-describedbyandaria-invalid. - Keep focus on the field that needs fixing.
If you prefer, the browser's built-in checks work too: attributes such as required and pattern stop the submit and show the browser's message, and formnovalidate on the Cancel button lets it through. Whichever you pick, validate again on the server, as covered in Secure Forms.
Try it in the lab: leave the name empty, then add a slash, then press Cancel.
Pattern 2: How a Dialog Gets Dismissedβ
A modal dialog can be closed in several ways. Know them, and decide which ones you allow.
| Way to close | What happens | Your control |
|---|---|---|
A method="dialog" submit | Closes with the button's value as returnValue | Check it first with a submit listener |
| The Escape key (modal) | Fires cancel, then closes | You can stop the cancel event, but do this rarely |
| A click on the backdrop | Nothing by default | Add a click handler, or use closedby |
dialog.close(value) | Closes straight away, with no cancel event | Call it from your own code |
dialog.requestClose(value) | Fires cancel first, then closes unless you stop it | Useful for "discard changes?" checks |
The closedby attributeβ
Newer browsers let you declare the rules in HTML:
<dialog closedby="any">...</dialog> <!-- Escape and click outside -->
<dialog closedby="closerequest">...</dialog> <!-- Escape only (the modal default) -->
<dialog closedby="none">...</dialog> <!-- only your own buttons -->
Support is still spreading, so check the Baseline label on MDN. Keep the click handler from the code above as a fallback, and make sure the two do not fight: if closedby="any" works, the extra handler just does the same thing again.
Asking before discarding workβ
If a dialog holds unsaved changes, you can intercept the Escape key:
dialog.addEventListener("cancel", (event) => {
if (hasUnsavedChanges()) {
event.preventDefault(); // stay open for now
showDiscardWarning(); // for example, an inline message with two buttons
}
});
Do not trap people. If you stop Escape, the dialog must offer another clear way out, such as a Cancel button. Browsers may also limit how often a page can block Escape, to prevent abuse, so do not rely on blocking it.
Click outside: the padding trapβ
The click-outside check is event.target === dialog. It works because a click on the backdrop reports the dialog itself as its target. But if the dialog element has padding, clicks on that padding also count as "outside". So set padding: 0 on the dialog, and put the padding on an inner element, as the lab does.
Pattern 3: Focus, Scrolling, and the Page Behindβ
Opening with showModal() already gives you a lot:
- Focus moves into the dialog, to the first focusable element, or to the one with
autofocus. - The page behind becomes inert, so keyboard users and screen readers cannot reach it. See inert for the attribute behind this idea.
- Focus returns to the element that opened the dialog when it closes. The lab logs this.
What you still decide:
- Where focus starts. For a delete confirmation, put
autofocuson the safe button. - Long content. Give the dialog a
max-heightand let its inner content scroll, so the buttons stay visible. - Background scrolling. In some browsers the page behind can still scroll under the backdrop. A small rule can stop that:
html:has(dialog:modal) {
overflow: hidden;
}
If a browser does not understand :has() here, nothing breaks. The page simply scrolls as before.
Pattern 4: A Gentle Animation (Optional)β
Dialogs appear and disappear instantly. Newer CSS features can animate that. This is a progressive enhancement: in a browser without them, the dialog just appears without animation, which is fine.
dialog {
opacity: 0;
transform: translateY(8px);
transition: opacity 0.2s, transform 0.2s,
overlay 0.2s allow-discrete, display 0.2s allow-discrete;
}
dialog[open] {
opacity: 1;
transform: none;
}
@starting-style {
dialog[open] { opacity: 0; transform: translateY(8px); }
}
dialog::backdrop {
background: rgb(0 0 0 / 0);
transition: background 0.2s, overlay 0.2s allow-discrete, display 0.2s allow-discrete;
}
dialog[open]::backdrop { background: rgb(0 0 0 / 0.5); }
@starting-style {
dialog[open]::backdrop { background: rgb(0 0 0 / 0); }
}
@media (prefers-reduced-motion: reduce) {
dialog, dialog::backdrop { transition: none; }
}
Always respect prefers-reduced-motion, as in the last rule. Check support for @starting-style and allow-discrete before you rely on the effect.
Pattern 5: Name It, and Describe Itβ
A dialog needs an accessible name, so screen readers announce what it is when it opens:
<dialog aria-labelledby="rename-title" aria-describedby="rename-help">
<h2 id="rename-title">Rename file</h2>
<p id="rename-help">Choose a new name for this file.</p>
</dialog>
For a confirmation that must interrupt, such as "Delete this account?", the role alertdialog fits. The earlier Dialog lesson covers when to use it.
Dialog, Popover, or Something Else?β
A dialog demands attention and, when modal, blocks the page. Many things that people build as dialogs do not need that.
| Need | Better fit |
|---|---|
| An answer is required before anything else happens | Modal dialog |
| A panel that should not block the page | Non-modal dialog, or a plain panel |
| A menu or small card that closes when you click elsewhere | Popover |
| Content that expands in place | Details and Summary |
| A message such as "Saved" | A plain element in a polite live region |
| A cookie or notice banner | A plain element, docked to an edge |
Use the Which One Fits? tab to practise. A page full of pop-ups tires people out, so use modals sparingly.
Dialogs in Frameworksβ
When you use a library, remember that the dialog's open state belongs to the browser:
- Keep the
dialogelement in the DOM, and callshowModal()from an event or an effect. - Do not control it with the
openattribute, because that opens a non-modal dialog without a backdrop. - Listen for
close, so your state follows what the browser does, including Escape.
Checking Your Setupβ
- Open the dialog with the keyboard, then Tab through it. Does focus stay inside?
- Press Escape. Does it close, and does focus return to the button that opened it?
- Open it with a screen reader if you can. Is the title announced?
- Try every way out: Cancel, Escape, click outside, and Save.
- Shrink the window and zoom to 200%. Can you still reach the buttons?
- Check right-to-left text and long translated labels.
- Look at the Console for errors when you open and close it quickly.
Best Practicesβ
- Use
showModal()for real pop-ups, never theopenattribute. - Give every dialog a heading and
aria-labelledby. - Validate before closing, and show errors inside the dialog.
- Always provide a visible Cancel or Close.
- Put
autofocuson the safe action in confirmations. - Set
padding: 0on the dialog if you handle click-outside. - Keep long content scrollable inside the dialog.
- Animate only as an enhancement, and respect reduced motion.
- Choose a popover or details when a dialog is more than you need.
- Use dialogs sparingly.
Quick Checklistβ
- Opened with
showModal(), notopen - Has a heading and an accessible name
- Focus starts in a sensible place and returns to the opener
- There is a visible way to cancel
- Errors are shown inside the dialog, and announced
- The Escape key is not trapped
- Works with the keyboard, at 200% zoom, and in right-to-left text
- Animation (if any) honours
prefers-reduced-motion - A dialog really is the right choice
Security and Privacy Notesβ
- A dialog is not a security boundary. Its content is in the page source even when it is closed, so never place secrets in a hidden dialog.
- A confirmation dialog is a convenience, not protection. The server must check permission for every sensitive action, whatever the visitor clicked. See Secure Forms.
- Never build dialog content from visitor text with
innerHTML. UsetextContent, as in XSS Basics. - Do not imitate system or browser dialogs. A dialog that pretends to be an operating system warning or a browser prompt is a phishing technique, and erodes trust.
- Be careful with dialogs inside frames. A form in a frame can be tricked with clickjacking. See iFrame Security.
Global Audience Notesβ
- Translated text is often longer. Do not fix the width of a dialog or its buttons. Use
max-widthand let content wrap. - Right-to-left languages mirror the layout. Use logical properties such as
margin-inlineandinset-inline, and test. - Button order and wording differ by culture and platform. Use clear, verb-based labels such as "Delete account" and "Keep account", not just "OK".
- Reduced motion and small screens matter more than you may think. Many visitors use older phones, and some are sensitive to motion.
- Plain language helps everyone, especially people reading in a second language.
Common Mistakes to Avoidβ
- Using
opento show a modal. - Letting a form close the dialog with an error still in it.
- Blocking Escape with no other way out.
- Putting padding on the dialog and breaking click-outside.
- No accessible name.
- Starting focus on a destructive button.
- Using a modal for a toast or a menu.
- Opening a dialog on page load.
- Relying on
closedbyalone where support is missing. - Animating without a reduced-motion rule.
Practice Timeβ
- Open the lab's dialog and press Cancel. What does the log say about
returnValueand focus? - Try an empty name, a name with a slash, and a name longer than forty characters. What happens each time?
- Press Escape. Which event is logged?
- Turn off "Close when the visitor clicks outside", and click the backdrop. What changes?
- Complete the Which One Fits? picker.
- Add a
requiredinput to a dialog of your own. Does the browser stop the submit? - Add a
cancellistener that stops Escape only when a flag is true. Always keep a Cancel button. - Bonus: add the optional animation, then add the reduced-motion rule and test it.
Quick Recapβ
Click a question to check your answer.
1. What is the top layer?
A special browser layer above the normal page. Modal dialogs live there, so z-index and overflow on other elements cannot hide or cover them.
2. How do you keep a form dialog open when the input is wrong?
Listen for submit on the form, let the Cancel button through, and call event.preventDefault() for a bad value. Show the error inside the dialog.
3. What is the difference between close() and requestClose()?
close() closes immediately. requestClose() fires a cancel event first, so your code can stop the close, for example to ask about unsaved changes.
4. Why can click-outside break if the dialog has padding?
Clicks on the dialog's own padding report the dialog as the target, the same as clicks on the backdrop. Put padding on an inner element instead.
5. What happens to focus with showModal()?
Focus moves into the dialog, the page behind becomes inert, and focus returns to the opening element when the dialog closes.
6. When should you not use a dialog?
For menus, tooltips, messages, banners, and expanding content. A popover, details, or a plain element is a better fit.
Key Takeawaysβ
- A modal dialog lives in the top layer, so you do not fight
z-index. - Validate on
submit, withpreventDefault()to keep it open. - Know every way out: submit, Escape, click outside,
close(), andrequestClose(). closedbydeclares dismissal rules, where supported.- Focus, naming, and a visible Cancel make a dialog accessible.
- Animation is optional, and must respect reduced motion.
- Pick the lightest tool: popover, details, or a plain element when you do not need a dialog.
Next up: Details and Summary, where you will build disclosure widgets and exclusive accordions without any JavaScript.