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.
The ontoggle attribute fires when the user opens or closes the <details> element.
The <details> tag is a new tag in HTML 5. The <details> tag specifies additional information or controls about documents that the user can view or hide on demand. The contents of the details tag is hidden by default.
The <details> HTML element creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state. A summary or label must be provided using the <summary> element.
Definition and UsageThe <summary> tag defines a visible heading for the <details> element. The heading can be clicked to view/hide the details. Note: The <summary> element should be the first child element of the <details> element.
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>
To test the current state, without events listeners, we can simply check if the attribute open
is set:
// Test onclick = () => { console.log( !detailElem.hasAttribute("open") ) }
<details id="detailElem"> <summary>Some details</summary> </details>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With