W3cubDocs

/Web APIs

HTMLDialogElement: cancel event

The cancel event fires on a <dialog> when the user instructs the browser that they wish to dismiss the current open dialog. The browser fires this event when the user presses the Esc key.

This event does not bubble.

When a <dialog> is dismissed with the Esc key, both the cancel and close events are fired.

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

Live example

HTML

html

<dialog class="example-dialog">
  <button class="close" type="reset">Close</button>
</dialog>

<button class="open-dialog">Open dialog</button>

<div class="result"></div>

JavaScript

js

const result = document.querySelector(".result");

const dialog = document.querySelector(".example-dialog");

dialog.addEventListener("cancel", (event) => {
  result.textContent = "dialog was canceled";
});

const openDialog = document.querySelector(".open-dialog");
openDialog.addEventListener("click", () => {
  if (typeof dialog.showModal === "function") {
    dialog.showModal();
    result.textContent = "";
  } else {
    result.textContent = "The dialog API is not supported by this browser";
  }
});

const closeButton = document.querySelector(".close");
closeButton.addEventListener("click", () => {
  dialog.close();
});

Result

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
cancel_event 37 79 98 No 24 15.4 No No 98 No 15.4 No

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/cancel_event