Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

html javascript expand <details> on mouseover and collapse on mouseout

<details> HTML element is collapsed by default and is expanded on mouse click. I am trying to override the default behavior so that it will be expanded on mouseover and collapsed on mouseout.

I would like to collapse only when the mouse is out of the both the internal details and the summary. How can it be achieved?

window.addEventListener("load", () => {
  const details = document.body.querySelectorAll("details");
  for (const detail of details) {
    detail.addEventListener("mouseover", (evt) => {
      console.log(evt.target.parentElement.setAttribute("open", true));
    });
    detail.addEventListener("mouseout", (evt) => {
      console.log(evt.target.parentElement.removeAttribute("open"));
    });
  }
});
<details>
  <summary>summary</summary>
  internal details
</details>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use mouseenter and mouseleave events instead of mouseover and mouseout. The later events bubble, so when you mouseout the <summary>, the event listener fires, but really, you’d only want the event listener to fire on the mouse leaving the <details> itself.

window.addEventListener("load", () => {
  const details = document.body.querySelectorAll("details");
  for (const detail of details) {
    detail.addEventListener("mouseenter", (evt) => {
      console.log(evt.target.setAttribute("open", true));
    });
    detail.addEventListener("mouseleave", (evt) => {
      console.log(evt.target.removeAttribute("open"));
    });
  }
});
<details>
  <summary>summary</summary>
  internal details
</details>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading