CKTIS / HTML
oncancel — handling the cancel event
The oncancel attribute contains code that runs when a cancel event is received. On a dialog element, it lets you respond to a close request and, when the event is cancelable, prevent closing.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
oncancel="JavaScript statements"
element.oncancel = function (event) { /* ... */ };oncancel is an event handler attribute for cancel, available on all HTML elements. Its value is JavaScript code, not an event name or a Boolean value. Its JavaScript counterpart is the element.oncancel property, which can be assigned a function or null.
A typical use is the dialog element: cancel signals a close request, not completed closing. The requestClose() method fires cancel first; the close() method skips that step. The close event instead reports closing.
When event.cancelable is true, event.preventDefault() prevents default closing. Returning false from an oncancel handler also cancels the event when it is cancelable. Do not assume every close request can be blocked.
The example opens a non-modal dialog and calls requestClose(). The attribute prevents closing, so the recorded result is open: true. The final close() removes the dialog from view without firing cancel again.
Examples
<!doctype html>
<meta charset="utf-8">
<title>oncancel</title>
<dialog id="demo" oncancel="event.preventDefault()">
<p>Dialog</p>
</dialog>
<pre id="result"></pre>
<script>
const demo = document.getElementById('demo');
const result = document.getElementById('result');
demo.show();
demo.requestClose();
result.textContent = `open: ${demo.open}`;
demo.close();
</script>Result
open: true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.