Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting the opening or closing of a details element [closed]

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.

like image 571
rolisz Avatar asked Sep 09 '11 14:09

rolisz


People also ask

Which of the following events is fired when the user opens or closes details element?

The ontoggle attribute fires when the user opens or closes the <details> element.

Which tag can be used to show or hide information or controls in a document?

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.

What is details element in HTML?

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.

What are details and summary tag?

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.


2 Answers

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>
like image 50
Daniel Herr Avatar answered Oct 05 '22 14:10

Daniel Herr


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>
like image 37
NVRM Avatar answered Oct 05 '22 14:10

NVRM