Project: Modal Dialog

Updated · 6 min read

A modal dialog interrupts the page to ask a question that needs an answer: "Delete this payment?", "Leave without saving?". Building one well used to take hundreds of lines (focus trapping, Escape, a backdrop, hiding the page from screen readers). With the <dialog> element and showModal(), the browser does most of it. This project builds a reusable confirmDialog() for the Fee Tracker that returns a promise, so any code can await the user's answer, and covers the details that make a modal pleasant and accessible.

What You'll Build

  • await confirmDialog({ title, message, confirmText, danger }) returns true or false.
  • Focus moves into the dialog on open and back to the button that opened it on close.
  • Escape and the Cancel button answer false; clicking the backdrop also cancels.
  • The question text is inserted safely; destructive actions get a red button and default focus on Cancel.
  • Only one dialog element, reused for every question.

Step 1: The HTML

dialog.html
<dialog id="confirm" aria-labelledby="confirm-title" aria-describedby="confirm-message">
  <form method="dialog">
    <h2 id="confirm-title"></h2>
    <p id="confirm-message"></p>
    <menu>
      <button value="cancel" id="confirm-cancel">Cancel</button>
      <button value="ok" id="confirm-ok">OK</button>
    </menu>
  </form>
</dialog>

aria-labelledby and aria-describedby tell screen readers the dialog's title and question. A <form method="dialog"> closes the dialog when either button is clicked, setting returnValue to the button's value, with no JavaScript needed for the buttons.

Step 2: The Promise-Based API

The function fills in the text, opens the dialog, and returns a promise resolved by the close event:

confirm-dialog.js
export function confirmDialog({ title, message, confirmText = "OK", danger = false }) {
  const dialog = document.querySelector("#confirm");
  dialog.querySelector("#confirm-title").textContent = title;
  dialog.querySelector("#confirm-message").textContent = message;
  const ok = dialog.querySelector("#confirm-ok");
  ok.textContent = confirmText;
  ok.classList.toggle("danger", danger);
 
  dialog.returnValue = "";
  dialog.showModal();
  (danger ? dialog.querySelector("#confirm-cancel") : ok).focus();
 
  return new Promise((resolve) => {
    dialog.addEventListener("close", () => resolve(dialog.returnValue === "ok"), { once: true });
  });
}

Key details:

DetailWhy
textContent for title and messageQuestions often include names from data; this prevents injection
Reset returnValue before openingEscape closes without setting it, so an old "ok" must not leak into the next answer
Focus Cancel for dangerous actionsPressing Enter by reflex shouldn't delete anything
{ once: true }Each question gets exactly one answer; no listener build-up

Step 3: Closing on Backdrop Click

A click on the dimmed backdrop is reported as a click on the <dialog> element itself, because the backdrop belongs to it. Clicks on the content inside have the inner element as their target. So:

backdrop.js
dialog.addEventListener("click", (event) => {
  if (event.target === dialog) dialog.close("cancel");
});

This works as long as the dialog's content (here, the <form>) fills the dialog's padding box; otherwise clicks on the dialog's own padding would also count as backdrop clicks. Style the dialog with padding: 0 and put the padding on the form.

Step 4: Styling

dialog.css
dialog { padding: 0; border: none; border-radius: 12px; max-width: min(90vw, 28rem); }
dialog form { padding: 1.25rem; }
dialog::backdrop { background: rgb(0 0 0 / 0.45); }
dialog menu { display: flex; justify-content: flex-end; gap: 0.5rem; padding: 0; }
button.danger { background: #b42318; color: white; }
@media (prefers-reduced-motion: no-preference) {
  dialog[open] { animation: pop 120ms ease-out; }
  @keyframes pop { from { transform: scale(0.96); opacity: 0; } }
}

The opening animation runs only for people who haven't asked for reduced motion.

The Complete Example

The Fee Tracker uses the dialog before deleting a payment and before marking a balance as waived. The checker deletes a payment (confirming), then cancels a waiver with Escape, then cancels another by clicking the backdrop:

modal-complete.html
<style>dialog { padding: 0; } dialog form { padding: 16px; } dialog::backdrop { background: rgb(0 0 0 / 0.45); }</style>
<ul id="payments"><li>Navika: $120</li><li>Advitha: $45</li></ul>
<button id="delete">Delete Navika's payment</button>
<button id="waive">Waive Advitha's balance</button>
<dialog id="confirm" aria-labelledby="confirm-title" aria-describedby="confirm-message">
  <form method="dialog">
    <h2 id="confirm-title"></h2>
    <p id="confirm-message"></p>
    <button value="cancel" id="confirm-cancel">Cancel</button>
    <button value="ok" id="confirm-ok">OK</button>
  </form>
</dialog>
<script type="module">
  const dialog = document.querySelector("#confirm");
  dialog.addEventListener("click", (e) => { if (e.target === dialog) dialog.close("cancel"); });

  function confirmDialog({ title, message, confirmText = "OK", danger = false }) {
    dialog.querySelector("#confirm-title").textContent = title;
    dialog.querySelector("#confirm-message").textContent = message;
    const ok = dialog.querySelector("#confirm-ok");
    ok.textContent = confirmText;
    ok.classList.toggle("danger", danger);
    dialog.returnValue = "";
    dialog.showModal();
    (danger ? dialog.querySelector("#confirm-cancel") : ok).focus();
    console.log(`asked: ${title} | focus on: ${document.activeElement.textContent}`);
    return new Promise((resolve) => dialog.addEventListener("close", () => resolve(dialog.returnValue === "ok"), { once: true }));
  }

  document.querySelector("#delete").addEventListener("click", async (e) => {
    const yes = await confirmDialog({ title: "Delete payment?", message: "Navika's $120 payment will be removed.", confirmText: "Delete", danger: true });
    if (yes) document.querySelector("#payments li").remove();
    console.log(`delete answered ${yes}; focus back on: ${document.activeElement.id}; rows: ${document.querySelectorAll("#payments li").length}`);
  });

  document.querySelector("#waive").addEventListener("click", async () => {
    const yes = await confirmDialog({ title: "Waive balance?", message: "Advitha's $45 balance will be set to $0." });
    console.log(`waive answered ${yes}`);
  });
</script>
Output
asked: Delete payment? | focus on: Cancel
delete answered true; focus back on: delete; rows: 1
asked: Waive balance? | focus on: OK
waive answered false
asked: Waive balance? | focus on: OK
waive answered false

The dangerous question focused Cancel; the safe one focused OK. After closing, focus returned to the button that opened the dialog, so keyboard users continue where they were. Escape and the backdrop click both answered false.

Practice

Challenge: Extend confirmDialog into promptDialog({ title, label }) that contains a text input and resolves with the entered text, or null when canceled. Here is the result-handling logic, testable on its own:

Show solution
prompt-result.js▶ Try it
function promptResult(returnValue, inputValue) {
  if (returnValue !== "ok") return null;
  const text = inputValue.trim();
  return text === "" ? null : text;
}
 
console.log(promptResult("ok", "  Paid by check "), promptResult("cancel", "x"), promptResult("ok", "   "));
Output
Paid by check null null

In the dialog, add <input id="prompt-input" required> to the form, and resolve with promptResult(dialog.returnValue, input.value) in the close listener.

Quick check: Modal project

3 questions
1Why reset dialog.returnValue before opening?
2How does the code detect a backdrop click?
3Why focus Cancel for a destructive action?

Key Takeaways

NeedCode
Open as modaldialog.showModal()
Answer from buttons<form method="dialog"> + value
Read the answerdialog.returnValue in close
Backdrop clickif (e.target === dialog) dialog.close("cancel")
Await an answernew Promise((r) => dialog.addEventListener("close", ..., { once: true }))

Was this tutorial helpful?

Lesson 135 of 139