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 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 is cancelable but can not bubble.
When a <dialog> is dismissed with the Esc key, both the cancel and close events are fired.
Use the event name in methods like addEventListener(), or set an event handler property.
addEventListener("cancel", (event) => { })
oncancel = (event) => { }
A generic Event.
<dialog class="example-dialog"> <button class="close">Close</button> </dialog> <button class="open-dialog">Open dialog</button> <div class="result"></div>
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();
});
| Specification |
|---|
| HTML> # event-cancel> |
| HTML> # handler-oncancel> |
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | WebView on iOS | |
cancel_event |
37 | 79 | 98 | 24 | 15.4 | 37 | 98 | 24 | 15.4 | 3.0 | 37 | 15.4 |
<dialog> element
© 2005–2025 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