HTMLDialogElement: cancel event

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨March 2022⁩.

The cancel event fires on a <dialog> element when the user sends a close request to the user agent.

Examples of close requests are:

  • Pressing the Esc key on desktop platforms
  • Calling the requestClose() method.
  • The back button on mobile platforms

This event is cancelable but can not bubble.

Syntax

Use the event name in methods like addEventListener(), or set an event handler property.

js
addEventListener("cancel", (event) => { })

oncancel = (event) => { }

Event type

A generic Event.

Examples

Canceling a dialog

The following example shows a button that, when clicked, opens a <dialog> via the showModal() method.

From there you can will trigger the cancel event by either clicking Request Close button to close the dialog (via the requestClose() method) or press the Esc key.

Preventing the dialog from closing is demonstrated with a checkbox.

HTML

html
<dialog id="dialog">
  <div>
    <label><input type="checkbox" id="prevent-close" /> prevent close</label>
  </div>
  <button type="button" id="request-close">Request Close</button>
</dialog>

<button id="open">Open dialog</button>
js
const dialog = document.getElementById("dialog");
const openButton = document.getElementById("open");
const requestCloseButton = document.getElementById("request-close");
const preventCloseInput = document.getElementById("prevent-close");

// Update button opens a modal dialog
openButton.addEventListener("click", () => {
  dialog.showModal();
});

// Request close
requestCloseButton.addEventListener("click", () => {
  // Triggers the cancel event
  dialog.requestClose();
});

// Fired when requestClose() is called
// Prevent the dialog from closing by calling event.preventDefault()
dialog.addEventListener("cancel", (event) => {
  if (preventCloseInput.checked) {
    log("Dialog close cancelled");
    event.preventDefault();
  }
});

dialog.addEventListener("close", (event) => {
  log("Dialog closed");
});

Result

Specifications

Specification
HTML
# event-cancel
HTML
# handler-oncancel

Browser compatibility

See also