How do you create a confirmation dialog with OK and Cancel buttons in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you create a confirmation dialog with OK and Cancel buttons in JavaScript?

message-square
0

To create a confirmation dialog with OK and Cancel buttons in JavaScript, use window.confirm(message) for a quick, blocking native browser prompt that returns true (OK) or false (Cancel/dismissed), or build an accessible custom modal dialog with a native <dialog> element (or ARIA role="dialog") and Promise-based resolution when you need custom styling, non-blocking async control, or rich content. Native confirm() is simple and synchronous, whereas a custom promise-backed modal avoids UI blocking and works consistently across browsers and designs.


1. Quick Native Confirmation with window.confirm()

Call window.confirm(message) to display a built-in browser confirmation box with OK and Cancel buttons, returning a boolean result:

// Ask for user confirmation using the built-in browser dialog
function confirmActionNative(message) {
  if (typeof message !== "string" || message.trim().length === 0) {
    throw new TypeError("Expected message to be a non-empty string.");
  }

  return window.confirm(message);
}

// Example usage:
const shouldDelete = confirmActionNative("Delete this draft permanently?");
console.log(shouldDelete); // true if OK clicked, false if Cancel or closed
  • Synchronous and blocking: Execution pauses while the dialog is open and resumes immediately with true or false.
  • Limited control: You cannot customize button labels, CSS styling, or layout, and some browsers or embedded contexts may suppress or style native dialogs differently.

2. Custom Accessible Modal with <dialog> and a Promise

For production web apps where you want custom styling, clear OK and Cancel controls, keyboard Escape handling, and non-blocking async/await flow, pair an HTML <dialog> element with a helper that resolves to true or false:

// Open a custom <dialog> confirmation modal and resolve to true (OK) or false (Cancel)
function openConfirmDialog(dialogEl, { message, okText = "OK", cancelText = "Cancel" } = {}) {
  if (!(dialogEl instanceof HTMLDialogElement)) {
    throw new TypeError("Expected dialogEl to be an HTMLDialogElement.");
  }

  if (typeof message !== "string" || message.trim().length === 0) {
    throw new TypeError("Expected message to be a non-empty string.");
  }

  const messageEl = dialogEl.querySelector("[data-dialog-message]");
  const okBtn = dialogEl.querySelector("[data-dialog-ok]");
  const cancelBtn = dialogEl.querySelector("[data-dialog-cancel]");

  if (!messageEl || !(okBtn instanceof HTMLButtonElement) || !(cancelBtn instanceof HTMLButtonElement)) {
    throw new Error("Dialog is missing required [data-dialog-message], [data-dialog-ok], or [data-dialog-cancel] elements.");
  }

  if (dialogEl.open) {
    return Promise.resolve(false);
  }

  messageEl.textContent = message;
  okBtn.textContent = okText;
  cancelBtn.textContent = cancelText;

  return new Promise((resolve) => {
    let settled = false;

    const finish = (confirmed) => {
      if (settled) return;
      settled = true;
      okBtn.removeEventListener("click", onOk);
      cancelBtn.removeEventListener("click", onCancel);
      dialogEl.removeEventListener("cancel", onNativeCancel);
      dialogEl.removeEventListener("close", onClose);
      if (dialogEl.open) {
        dialogEl.close();
      }
      resolve(confirmed);
    };

    const onOk = (event) => {
      event.preventDefault();
      finish(true);
    };

    const onCancel = (event) => {
      event.preventDefault();
      finish(false);
    };

    const onNativeCancel = (event) => {
      event.preventDefault();
      finish(false);
    };

    const onClose = () => {
      finish(false);
    };

    okBtn.addEventListener("click", onOk);
    cancelBtn.addEventListener("click", onCancel);
    dialogEl.addEventListener("cancel", onNativeCancel);
    dialogEl.addEventListener("close", onClose);

    dialogEl.showModal();
  });
}

// Example usage (with <dialog id="confirm-modal"> containing [data-dialog-message], [data-dialog-ok], [data-dialog-cancel]):
async function handlePublish() {
  const modal = document.querySelector("#confirm-modal");
  if (!modal) return;

  const confirmed = await openConfirmDialog(modal, {
    message: "Publish changes to production?",
    okText: "OK",
    cancelText: "Cancel"
  });

  console.log("Confirmed:", confirmed); // true or false
}
  • Clean event cleanup: Removing listeners after resolution prevents duplicate handlers or memory leaks across repeated openings.
  • Native modal trap & Escape support: dialogEl.showModal() renders in the top layer, blocks background clicks, and fires "cancel" when the user presses Escape.

3. Choosing Between window.confirm() and a Custom Dialog

Pick the simplest mechanism that fits your UX requirements without over-engineering small utilities or blocking async apps:

// Choose native confirm() for quick scripts or custom dialog for UI apps
async function requestConfirmation(options) {
  if (options?.useNative) {
    return confirmActionNative(options.message);
  }

  return openConfirmDialog(options.dialogEl, options);
}

// Example usage:
console.log(typeof requestConfirmation); // "function"
  • Use window.confirm() for quick prototypes, admin scripts, or simple synchronous checks where native browser UI is acceptable.
  • Use <dialog> + Promise for polished UI components, custom OK/Cancel styling, and async/await workflows.

TL;DR: Use window.confirm(message) for a quick boolean OK/Cancel prompt (true on OK, false on Cancel), or use <dialog>.showModal() wrapped in a Promise for customizable, accessible, non-blocking async/await confirmations.