View video tutorial

HTML ontoggle Attribute

HTML

The HTML ontoggle attribute is an event handler used to specify a script that will run when the user opens or closes a <details> element.

Definition and Usage


➔ The <details> element is used to specify additional details that the user can view or hide as needed.

➔ The event object associated with this event is a ToggleEvent, whose oldState and newState properties are either "open" or "closed".

Syntax
//In HTML
<details ontoggle="myFunction()" id="sample">
  <summary>Click to see details</summary>
  <p>Here are the additional details.</p>
</details>

//In javascript
document.getElementById("sample").ontoggle=function() {myFunction();};
//OR
document.getElementById("sample").addEventListener("toggle", myFunction);
//OR 
document.getElementById("sample").addEventListener("toggle", (event) => {
    myFunction();
 });

Applies to

This attribute can be used on the following element.

Attribute Element
ontoggle <details>

Example

<!DOCTYPE html>
<html>
<head>
    <title>HTML ontoggle attribute example</title>
</head>
<body>
    <h3>HTML ontoggle attribute example</h3>
    <p>Open and close the details element to trigger the event.</p>
    <details ontoggle="myFunction(event)">
        <summary>Click to see details</summary>
        <p>Here are the additional details</p>
    </details>
    <script>
        function myFunction(e) {
            alert('Details: ' + e.newState);
        }
    </script>
</body>
</html>
Try it Now »

Click on the "Try it Now" button to see how it works.