Favorites

HTML oncancel Event Attribute

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
oncancel
HTML Event AttributeThis event attribute is supported by all modern browsers.
Updated 22nd November 2026

Description

The oncancel event attribute runs a script when a <dialog> element is dismissed by the user, for example by pressing the Esc key, or when a <dialog closedby="any"> is closed by clicking outside it. It does not fire when the dialog is closed with the close() method or a form with method="dialog".

The event is cancelable: calling event.preventDefault() keeps the dialog open, which is useful when it holds unsaved data. Browsers may ignore this when the user presses Esc repeatedly without interacting with the page, so that a dialog cannot trap the user.

The cancel event also fires on <input type="file"> elements when the user closes the file picker without choosing a file or without changing the selection.

<dialog oncancel="return confirm('Discard your changes?')">...</dialog>

Syntax

<element oncancel="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html>
<html>
<head>
<title>oncancel event</title>
</head>
<body>
<button onclick="document.getElementById('dlg').showModal()">Open dialog</button>
<dialog id="dlg" oncancel="log('cancel: the dialog was dismissed')" onclose="log('close: returnValue = ' + this.returnValue)">
<p>Press Esc or click Close.</p>
<button onclick="this.closest('dialog').close('closed')">Close</button>
</dialog>
<ul id="log"></ul>
<script>
function log(text) {
var li = document.createElement("li");
li.textContent = text;
document.getElementById("log").appendChild(li);
}
</script>
</body>
</html>
Open in editor

Browser Support

The following information will show you the current browser support for the HTML oncancel event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.

This event attribute is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee