javascripthtml

Detecting the opening or closing of a details element


How can I detect when a details element is opened or closed in Javascript? Other than attaching a listener to the click function and checking if the open attribute is set or not.


Solution

  • You can use the toggle event:

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/toggle_event

    details.addEventListener("toggle", function() {
     if(details.open) {
      summary.textContent = "toggle event: open"
     } else {
      summary.textContent = "toggle event: closed"
     }
    })
    <!doctype html>
    <details id="details">
     <summary id="summary">toggle event: closed</summary>
     details
    </details>