How to handle expand/collapse event of Html5 <details> element?

Issue

I use details/summary elements to get an expandable section:

https://www.w3schools.com/TAGS/tag_details.asp

d3.select('details')
  .on('click',()=>{
     alert('clicked');
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<details>
  <summary>Header</summary>
  <p>Content</p>
  <p>Content</p>
</details>

I want to execute an action when the open state of the details element is toggled. How can I do so?

If I would use the onclick event, the event is also fired if a user clicks on the summary or the content. I only want to handle “clicks on the toggle arrow”.

Solution

d3.select('details')
  .on('toggle',()=>{
     alert('clicked');
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<details>
  <summary>Header</summary>
  <p>Content</p>
  <p>Content</p>
</details>

Answered By – Stefan

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.