HTMLElement: cancel event
The cancel
event is fired by <input>
and <dialog>
elements. The event is fired when the user cancels the currently open dialog by closing it with the Esc key. It is also fired by the file input when the user cancels the file picker dialog via the Esc key or the cancel button and when the user re-selects the same files that were previously selected.
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.
addEventListener("cancel", (event) => {});
oncancel = (event) => {};
Event type
A generic Event
.
Examples
Canceling a dialog
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
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
Canceling an input element
HTML
<label for="file">Select or file. Or don't.</label>
<input type="file" id="file" name="file" />
<div id="result"></div>
JavaScript
const elem = document.getElementById("file");
const result = document.getElementById("result");
elem.addEventListener("cancel", () => {
result.textContent = "Canceled.";
});
elem.addEventListener("change", () => {
if (elem.files.length == 1) {
result.textContent = "File Selected.";
}
});
Result
Open the file selector, then close the selection dialog with the escape key or the cancel button. Both of these will cause the cancel event to be fired. Also, try selecting a local file on your machine; then reopen the file selection window and reselect the same file. This too causes the cancel event to be fired.
Specifications
No specification found
No specification data found for api.HTMLElement.cancel_event
.
Check for problems with this page or contribute a missing spec_url
to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.
Browser compatibility
BCD tables only load in the browser