When someone interacts with a webpage, the browser sends events to the relevant JavaScript code. The cancel event happens when a dialog is requested to close, for example by pressing Escape.
When cancel happens
A dialog is requested to close, for example by pressing Escape.
You can listen for it using addEventListener(). That keeps event handling separate from HTML attributes such as onclick and works well with modern code organization.
A small working example
<dialog id="demo-target">
<p>Press Escape to close this dialog.</p>
<form method="dialog"><button>Close</button></form>
</dialog>
<button type="button" id="open-dialog">Open dialog</button>
<p id="event-status" role="status">Waiting for cancel...</p>
<script>
const eventTarget = document.getElementById("demo-target");
const eventStatus = document.getElementById("event-status");
if (eventTarget) {
eventTarget.addEventListener("cancel", (eventDetails) => {
eventStatus.textContent = "cancel event received";
console.log(eventDetails.type, eventDetails.target);
});
}
document.getElementById("open-dialog").addEventListener("click", () => {
eventTarget.showModal();
});
</script>
Reading the code
The browser listens for cancel on the relevant target. When the event occurs, the callback receives eventDetails, updates the status message and logs the event name and target in Developer Tools.
Open a modal dialog using showModal(), then press Escape.
Try it in your browser
Open the page, show the Console panel, and follow this test: Open a modal dialog using showModal(), then press Escape. Then change one thing in the example and observe whether the event still fires.
Common Beginner Mistakes
- Expecting
cancelto fire without its required user action or browser condition. - Open a modal dialog using showModal(), then press Escape.
- Adding repeated event listeners without considering cleanup or unwanted side effects.
Key Takeaways
cancelreports a dialog is requested to close, for example by pressing Escape.addEventListener("cancel", ...)listens for the event on the appropriate target.- Open a modal dialog using showModal(), then press Escape.