The HTML oncancel event
The HTML oncancel attribute runs JavaScript when the user dismisses a <dialog> (e.g. with the Escape key). It is an inline handler for the cancel event; in modern code prefer addEventListener('cancel', …).
Overview
The oncancel event attribute runs JavaScript when a dialog is canceled. In JavaScript the event itself is named cancel. Drop the on prefix when you call addEventListener.
It relates to native disclosure and dialog widgets (the <dialog> element, <details>, and popovers), letting you react when they open, close or are dismissed without wiring up the behavior yourself.
You can wire this up with the inline oncancel HTML attribute, but the modern, recommended approach is element.addEventListener('cancel', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<element oncancel="handler()">…</element>
element.addEventListener('cancel', handler);
Best practices
- Prefer
element.addEventListener('cancel', handler)over the inlineoncancelattribute; it separates behavior from markup and allows multiple handlers. - Prefer the native <dialog>, <details> and popover APIs that fire these events over hand-built widgets.
- Use the event to sync state, for example to lazy-load content when a panel opens.
- Keep these widgets accessible: manage focus and provide an accessible name.
Frequently asked questions
What is the oncancel event?
cancel.Which elements fire this event?
Can I stop the dialog from closing?
event.preventDefault() in the cancel handler and the dialog stays open.Should I use the oncancel attribute or addEventListener?
element.addEventListener('cancel', …) in JavaScript. The inline oncancel attribute works but mixes behavior into the markup and allows only one handler per element.