Execute a script when the user opens or closes the element in HTML?

The ontoggle event in HTML is triggered when a user opens or closes the <details> element. This event allows you to execute JavaScript functions whenever the disclosure state of a details element changes, making it useful for tracking user interactions or updating content dynamically.

Syntax

Following is the syntax for the ontoggle event attribute −

<details ontoggle="functionName()">
   <summary>Summary text</summary>
   Content to be shown/hidden
</details>

The ontoggle event fires both when the details element is opened (expanded) and when it is closed (collapsed).

Basic Example

Following example demonstrates the basic usage of the ontoggle event −

<!DOCTYPE html>
<html>
<head>
   <title>ontoggle Event Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Office Details</h2>
   <p>You need to join office from Feb 23</p>
   <details ontoggle="display()">
      <summary>More Information</summary>
      <p>Timings: 9:00 AM to 5:30 PM</p>
      <p>Office location: Hyderabad</p>
      <p>Contact: +91-40-12345678</p>
   </details>
   
   <script>
      function display() {
         alert("Details section toggled! Check timings and location.");
      }
   </script>
</body>
</html>

When you click on "More Information", an alert appears indicating the details section has been toggled.

Detecting Open/Close State

You can determine whether the details element is being opened or closed by checking the open property of the element.

Example

<!DOCTYPE html>
<html>
<head>
   <title>Toggle State Detection</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Course Details</h2>
   <details id="courseDetails" ontoggle="checkState(this)">
      <summary>HTML5 Course Information</summary>
      <p>Duration: 4 weeks</p>
      <p>Price: $199</p>
      <p>Difficulty: Beginner</p>
   </details>
   
   <p id="status">Status: Closed</p>
   
   <script>
      function checkState(element) {
         var status = document.getElementById("status");
         if (element.open) {
            status.textContent = "Status: Course details are now visible";
            status.style.color = "green";
         } else {
            status.textContent = "Status: Course details are now hidden";
            status.style.color = "red";
         }
      }
   </script>
</body>
</html>

The status message changes based on whether the details element is open or closed −

Status: Course details are now visible  (when opened, green text)
Status: Course details are now hidden   (when closed, red text)

Multiple Details Elements

When working with multiple details elements, you can use the same function and differentiate between them using parameters or element properties.

Example

<!DOCTYPE html>
<html>
<head>
   <title>Multiple Details Elements</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Tutorial Sections</h2>
   
   <details ontoggle="logToggle('HTML')">
      <summary>HTML Tutorial</summary>
      <p>Learn HTML tags, attributes, and structure.</p>
   </details>
   
   <details ontoggle="logToggle('CSS')">
      <summary>CSS Tutorial</summary>
      <p>Learn styling, layouts, and responsive design.</p>
   </details>
   
   <details ontoggle="logToggle('JavaScript')">
      <summary>JavaScript Tutorial</summary>
      <p>Learn programming, DOM manipulation, and events.</p>
   </details>
   
   <div id="log" style="margin-top: 20px; padding: 10px; background-color: #f0f0f0;">
      <h3>Activity Log:</h3>
      <p id="logContent">No activity yet</p>
   </div>
   
   <script>
      function logToggle(section) {
         var logContent = document.getElementById("logContent");
         var timestamp = new Date().toLocaleTimeString();
         logContent.textContent = section + " section toggled at " + timestamp;
      }
   </script>
</body>
</html>

Each details element logs its toggle activity with a timestamp, allowing you to track which sections users are accessing.

ontoggle Event Flow User clicks <summary> element ontoggle event is triggered JavaScript function executes States open = true (expanded) open = false (collapsed)

Event Object Properties

The toggle event provides an event object that contains useful information about the toggle action.

Example

<!DOCTYPE html>
<html>
<head>
   <title>Event Object Properties</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>FAQ Section</h2>
   
   <details ontoggle="handleToggle(event)">
      <summary>What is HTML5?</summary>
      <p>HTML5 is the latest version of the HTML markup language.</p>
   </details>
   
   <div id="eventInfo" style="margin-top: 20px; padding: 10px; background-color: #f9f9f9; border-left: 4px solid #007bff;">
      <h4>Event Information:</h4>
      <p id="info">Click the summary to see event details</p>
   </div>
   
   <script>
      function handleToggle(event) {
         var info = document.getElementById("info");
         var target = event.target;
         info.innerHTML = 
            "<strong>Event Type:</strong> " + event.type + "<br>" +
            "<strong>Element Tag:</strong> " + target.tagName + "<br>" +
            "<strong>Is Open:</strong> " + target.open + "<br>" +
            "<strong>Timestamp:</strong> " + new Date().toLocaleString();
      }
   </script>
</body>
</html>

This example displays detailed information about the toggle event, including the event type, target element, open state, and timestamp.

Practical Use Cases

The ontoggle event is commonly used for −

  • Analytics tracking − Monitor which sections users expand to understand content engagement.

  • Lazy loading − Load content only when a details section is opened to improve page performance.

  • Form validation − Trigger validation when users expand sections containing form fields.

  • Accessibility − Announce state changes to screen readers for better accessibility.

Conclusion

The ontoggle event provides a simple way to execute JavaScript when users interact with <details> elements. By checking the open property, you can determine the current state and respond appropriately, making it useful for creating interactive and dynamic web content.

Updated on: 2026-03-16T21:38:53+05:30

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements