CKTIS / HTML
onclose — handling a close event
The onclose attribute contains JavaScript that handles the close event. A typical use is responding when a dialog element closes, for example by reading its returnValue. It is not a mechanism for preventing closure.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
onclose="JavaScript statements"onclose is a global event handler attribute for close. Its value is JavaScript code, not a boolean. It can be written on any HTML element, but adding the attribute does not itself make an element emit this event.
A typical use is the dialog element. Calling close() closes an open dialog and queues a close event. Inside the attribute handler, this refers to the element, and event provides the event object. Read the closing result through this.returnValue.
A dialog element's close event does not bubble and cannot be canceled. To prevent a close request, handle the cancelable cancel event; close() itself bypasses that stage. Manually removing the open attribute does not fire close.
Distinguish the attribute from the JavaScript property element.onclose, which takes a function, and from addEventListener('close', handler), which allows multiple listeners. In the example, the handler reads the result done and updates the text only after the queued event is delivered.
Examples
<!doctype html>
<meta charset="utf-8">
<title>onclose</title>
<dialog id="demo" onclose="document.getElementById('result').textContent = 'closed: ' + this.returnValue">
<p>Dialog</p>
</dialog>
<output id="result">waiting</output>
<script>
const dialog = document.getElementById('demo');
dialog.show();
dialog.close('done');
</script>Result
closed: done
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.