Detecting the opening or closing of a details element

rolisz picture rolisz · Sep 9, 2011 · Viewed 7.5k times · Source

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.

Answer

Daniel Herr picture Daniel Herr · Mar 22, 2016

You can use the toggle event:

var details = document.querySelector("details")

details.addEventListener("toggle", function() {
 details.firstChild.textContent = "done"
})
<!doctype html>
<details>
 <summary>toggle event</summary>
</details>