Automatically close all the other <details> tags after opening a specific <details> tag
Another approach, slightly shorter, slightly more efficient, without dependencies, and without onclick attributes in the HTML.
// Fetch all the details element.
const details = document.querySelectorAll("details");
// Add the onclick listeners.
details.forEach((targetDetail) => {
targetDetail.addEventListener("click", () => {
// Close all the details that are not targetDetail.
details.forEach((detail) => {
if (detail !== targetDetail) {
detail.removeAttribute("open");
}
});
});
});
<details>
<summary>1</summary>Demo 1
</details>
<details>
<summary>2</summary>Demo 2
</details>
<details>
<summary>3</summary>Demo 3
</details>
Same concept, just a bit shorter.
$('details').click(function (event) {
$('details').not(this).removeAttr("open");
});
Whao, nobody answering about <details>
<summary>
are using toogle
event ?
const All_Details = document.querySelectorAll('details');
All_Details.forEach(deet=>{
deet.addEventListener('toggle', toggleOpenOneOnly)
})
function toggleOpenOneOnly(e) {
if (this.open) {
All_Details.forEach(deet=>{
if (deet!=this && deet.open) deet.open = false
});
}
}
<details>
<summary>1</summary>
Demo 1
</details>
<details>
<summary>2</summary>
Demo 2
</details>
<details>
<summary>3</summary>
Demo 3
</details>