<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>
>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>