Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

ontoggle — handling open-state changes

The ontoggle attribute contains JavaScript that handles the toggle event after an element's open state changes. Relevant elements include details, dialog, and elements acting as popovers. The attribute does not itself open or close an element.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

ontoggle="JavaScript statements"
element.ontoggle = (event) => { /* handler */ };
element.addEventListener("toggle", (event) => { /* listener */ });

ontoggle is an event handler content attribute for toggle; its value is JavaScript code, not a Boolean. It is available on HTML elements, but adding it does not create disclosure behavior. The event is generated for state changes of details, dialog, and elements acting as a popover.

Inside the attribute code, event refers to the event and this refers to the element handling it. The ToggleEvent object provides oldState and newState, with values of "open" or "closed". toggle reports a completed change: it does not bubble and is not cancelable. preventDefault() will not undo the change.

Notification is queued, and rapid successive changes can be coalesced into one event. Do not assume one handler call for every state change. beforetoggle is a separate event dispatched before a change by mechanisms that support it; it is not an earlier form of toggle available for every details change.

In JavaScript, you can assign a function to the element.ontoggle property; another assignment replaces the previous function in that handler slot. addEventListener("toggle", handler) registers independent listeners. The example uses the attribute to demonstrate its syntax: the script opens details, and the handler updates the text when the event is delivered.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>ontoggle example</title>
<details id="panel" ontoggle="document.getElementById('status').textContent = event.oldState + ' -> ' + event.newState">
  <summary>Details</summary>
  <p>Extra information.</p>
</details>
<pre id="status">Waiting</pre>
<script>
  document.getElementById('panel').open = true;
</script>
</html>

Result

closed -> open

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources