Dialogs and Popups

Updated · 7 min read
mediumES2026javascriptdialogmodalalertaccessibility

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) (returns true/false) and prompt(msg) (returns text or null) 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, setting dialog.returnValue to the clicked button's value.
  • The close event tells you when and how it closed.

The Older Built-In Popups

FunctionShowsReturns
alert(message)A message and an OK buttonundefined
confirm(message)A message, OK and Canceltrue for OK, false for Cancel
prompt(message, default)A message, a text box, OK and CancelThe text, or null for Cancel
older-popups.js
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:

ProblemWhy it matters
They block everythingNo JavaScript runs, no animation, no network callbacks, until the user answers
No stylingThey look like the browser, not your app, and wording like "This page says" can't be changed
Can be suppressedBrowsers let users stop a page from showing more popups; then confirm returns false without asking
Limited inputprompt only collects one line of text, with no validation
Unavailable in some contextsSandboxed 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:

MethodOpens 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
dialog.html
<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>
Output
open: true | focused: cancel
closed with: delete | open: false

Explanation: 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:

FeatureshowModal() 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 closedYes
Closes on Escape (firing a cancel event first)Yes
Announces it as a dialog to screen readersYes
Adds a ::backdrop you can styleYes
escape.html
<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>
Output
Escape pressed
closed; focus back on: open

Forms 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:

form-dialog.html
<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>
Output
Saved $85

The 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):

backdrop.js
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:

ask.html
<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>
Output
Payment deleted

The 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
note-dialog.html
<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>
Output
Paid by check

Quick check: Dialogs

3 questions
1What does confirm("Delete?") return when the user clicks Cancel?
2Which method opens a dialog as a modal with an inert background?
3What does a form with method="dialog" do when submitted?

Key Takeaways

TaskCode
Open as modaldialog.showModal()
Close with a resultdialog.close("save")
Read the resultdialog.returnValue in a close listener
Form that closes it<form method="dialog">
React to Escapedialog.addEventListener("cancel", ...)

Was this tutorial helpful?

Lesson 81 of 139