Dialogs and Popups
A dialog is a box that appears over the page to show a message or ask a question: "Delete this payment?", "Enter the amount". Browsers have three built-in popup functions, alert, confirm and prompt, which are simple but block the whole page and can't be styled. The modern replacement is the HTML <dialog> element: a real part of your page that you open with JavaScript, style with CSS, and that the browser makes accessible for you, including focus handling and the Escape key.
In One Minute
alert(msg),confirm(msg)(returnstrue/false) andprompt(msg)(returns text ornull) are older: they freeze the page and can't be styled.<dialog>is the modern way:dialog.showModal()opens it as a modal,dialog.close(value)closes it.- A modal dialog makes the rest of the page inert, traps focus inside, and closes on Escape automatically.
- A
<form method="dialog">inside a dialog closes it on submit, settingdialog.returnValueto the clicked button's value. - The
closeevent tells you when and how it closed.
The Older Built-In Popups
| Function | Shows | Returns |
|---|---|---|
alert(message) | A message and an OK button | undefined |
confirm(message) | A message, OK and Cancel | true for OK, false for Cancel |
prompt(message, default) | A message, a text box, OK and Cancel | The text, or null for Cancel |
alert("Payment saved.");
if (confirm("Delete Srihitha's payment of $85?")) {
deletePayment();
}
const amount = prompt("Amount paid:", "120");
if (amount !== null) recordPayment(Number(amount));They are easy, which is why you'll see them in tutorials and quick tools. But they have real problems:
| Problem | Why it matters |
|---|---|
| They block everything | No JavaScript runs, no animation, no network callbacks, until the user answers |
| No styling | They look like the browser, not your app, and wording like "This page says" can't be changed |
| Can be suppressed | Browsers let users stop a page from showing more popups; then confirm returns false without asking |
| Limited input | prompt only collects one line of text, with no validation |
| Unavailable in some contexts | Sandboxed iframes and some embedded browsers ignore them |
Because they block the main thread, they don't work in this course's checker or in the Try it runner, so this example is shown without output.
The <dialog> Element
<dialog> is an HTML element that is hidden until opened. JavaScript opens it in one of two ways:
| Method | Opens as |
|---|---|
dialog.showModal() | A modal: over everything, with a backdrop; the rest of the page can't be clicked or focused |
dialog.show() | A non-modal: the page stays usable (like a floating panel) |
dialog.close(returnValue?) | Closes it, optionally setting dialog.returnValue |
<button id="open">Delete payment</button>
<dialog id="confirm-delete">
<p>Delete Srihitha's payment of $85?</p>
<button id="cancel">Cancel</button>
<button id="confirm">Delete</button>
</dialog>
<script>
const dialog = document.querySelector("#confirm-delete");
document.querySelector("#open").addEventListener("click", () => {
dialog.showModal();
console.log("open:", dialog.open, "| focused:", document.activeElement.id);
});
document.querySelector("#cancel").addEventListener("click", () => dialog.close("cancel"));
document.querySelector("#confirm").addEventListener("click", () => dialog.close("delete"));
dialog.addEventListener("close", () => {
console.log("closed with:", dialog.returnValue, "| open:", dialog.open);
});
</script>open: true | focused: cancel
closed with: delete | open: falseExplanation: showModal() opened the dialog and moved focus to its first focusable element (the Cancel button). Clicking Delete closed it with the value "delete", which the close event handler read from dialog.returnValue. Unlike confirm, nothing blocked the page while the dialog was open; your code reacts to the close event instead of waiting.
What a Modal Dialog Gives You
showModal() handles the hard accessibility work that hand-made popups often get wrong:
| Feature | showModal() does it |
|---|---|
| Puts the dialog above everything (the "top layer") | Yes |
| Makes the rest of the page inert (not clickable or focusable) | Yes |
| Moves focus into the dialog, and back to the opener when closed | Yes |
Closes on Escape (firing a cancel event first) | Yes |
| Announces it as a dialog to screen readers | Yes |
Adds a ::backdrop you can style | Yes |
<button id="open">Details</button>
<dialog id="d"><p>Tuition $400</p><button>OK</button></dialog>
<script>
const d = document.querySelector("#d");
document.querySelector("#open").addEventListener("click", () => d.showModal());
d.addEventListener("cancel", () => console.log("Escape pressed"));
d.addEventListener("close", () => console.log("closed; focus back on:", document.activeElement.id));
</script>Escape pressed
closed; focus back on: openForms Inside Dialogs
A form with method="dialog" closes its dialog when submitted, instead of sending data to a server. The submit button's value becomes the dialog's returnValue, and the browser's validation still runs:
<button id="open">Record payment</button>
<dialog id="pay">
<form method="dialog">
<label>Amount <input id="amount" name="amount" type="number" min="1" required></label>
<button value="cancel" formnovalidate>Cancel</button>
<button id="save" value="save">Save</button>
</form>
</dialog>
<script>
const pay = document.querySelector("#pay");
document.querySelector("#open").addEventListener("click", () => pay.showModal());
pay.addEventListener("close", () => {
if (pay.returnValue !== "save") return console.log("canceled");
const amount = new FormData(pay.querySelector("form")).get("amount");
console.log(`Saved $${amount}`);
});
</script>Saved $85The Cancel button has formnovalidate, so it can close the dialog even while the required field is empty.
Closing When the Backdrop Is Clicked
Modal dialogs don't close on a backdrop click by default. Newer browsers support the attribute closedby="any" for that; a portable way is to check whether the click landed on the dialog element itself (the backdrop area counts as the dialog):
dialog.addEventListener("click", (event) => {
if (event.target === dialog) dialog.close("dismiss");
});This works when the dialog's content is wrapped in an inner element, so clicks on the content have a different target.
Popovers
For lighter UI that doesn't need to block the page (menus, tooltips, small panels), HTML also has the popover attribute. A button with popovertarget toggles it with no JavaScript, and it closes when the user clicks elsewhere or presses Escape. JavaScript can control it with element.showPopover(), hidePopover() and togglePopover(). Use <dialog> with showModal() when the user must respond; use a popover for everything else that floats.
In Practice
The Fee Tracker wraps the dialog in a small function that returns a promise, so calling code can await an answer just as easily as with confirm, without blocking the page:
<button id="delete">Delete Advitha's payment</button>
<dialog id="dlg">
<p id="question"></p>
<form method="dialog">
<button value="no">Keep it</button>
<button value="yes">Delete</button>
</form>
</dialog>
<script>
function ask(question) {
const dlg = document.querySelector("#dlg");
dlg.querySelector("#question").textContent = question;
dlg.showModal();
return new Promise((resolve) => {
dlg.addEventListener("close", () => resolve(dlg.returnValue === "yes"), { once: true });
});
}
document.querySelector("#delete").addEventListener("click", async () => {
const ok = await ask("Delete Advitha's payment of $45?");
console.log(ok ? "Payment deleted" : "Payment kept");
});
</script>Payment deletedThe question is set with textContent, so a student name containing HTML can't inject anything. Promises and await are covered in the async chapter.
Common Mistakes
Using confirm for important flows. It blocks the page, can be suppressed, and can't be styled. Use <dialog>.
Building modals from <div>s. Focus trapping, Escape, inertness and screen reader support are easy to get wrong. Use showModal().
Opening with show() when you need a modal. show() leaves the page interactive and has no backdrop.
Forgetting formnovalidate on Cancel. Required fields stop the dialog from closing.
Practice
Challenge: Make a dialog with a text input for a note and Save and Cancel buttons using method="dialog". Log the note when saved, or "canceled" otherwise.
Show solution
<button id="open">Add note</button>
<dialog id="d">
<form method="dialog">
<input id="note" name="note">
<button value="cancel">Cancel</button>
<button id="ok" value="save">Save</button>
</form>
</dialog>
<script>
const d = document.querySelector("#d");
document.querySelector("#open").addEventListener("click", () => d.showModal());
d.addEventListener("close", () => {
console.log(d.returnValue === "save" ? d.querySelector("#note").value : "canceled");
});
</script>Paid by checkKey Takeaways
| Task | Code |
|---|---|
| Open as modal | dialog.showModal() |
| Close with a result | dialog.close("save") |
| Read the result | dialog.returnValue in a close listener |
| Form that closes it | <form method="dialog"> |
| React to Escape | dialog.addEventListener("cancel", ...) |
Was this tutorial helpful?