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.
Thecancel 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 theEsc key.
This event is cancelable but can not bubble.
When a<dialog> is dismissed with theEsc key, both thecancel andclose events are fired.
In this article
Syntax
Use the event name in methods likeaddEventListener(), or set an event handler property.
js
addEventListener("cancel", (event) => { })oncancel = (event) => { }Event type
A genericEvent.
Examples
>Canceling a dialog
HTML
html
<dialog> <button>Close</button></dialog><button>Open dialog</button><div></div>button,div { margin: 0.5rem;}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
| Specification |
|---|
| HTML> # event-cancel> |
| HTML> # handler-oncancel> |
Browser compatibility
See also
- HTML
<dialog>element