Accordions - One Open at a Time
Multiple accordions on a post, but only one is open at a time...
One
๐
Two
๐๐
Three
๐๐๐
Uno
๐
Dos
๐๐
Tres
๐๐๐
Un
๐ค
Deux
๐ค๐ค
Trois
๐ค๐ค๐ค
The CSS...
<style>
.flex {
display: flex;
gap: 1rem;
}
.flex > div {
margin: 0;
width: 33%;
border: 1px solid #333;
background-color: rgb(0,0,0,.0625);
padding: 0.25rem .5rem;
}
</style>
The HTML...
<div class=flex>
<div class=accordion>
<details>
<summary>One</summary>
<div aria-label=Yes>๐</div>
</details>
<details>
<summary>Two</summary>
<div aria-label="Yes, yes">๐๐</div>
</details>
<details>
<summary>Three</summary>
<div aria-label="Yes, yes, yes">๐๐๐</div>
</details>
</div>
<div class=accordion lang=es>
<details>
<summary>Uno</summary>
<div aria-label=Bueno>๐</div>
</details>
<details>
<summary>Dos</summary>
<div aria-label="Bueno, bueno">๐๐</div>
</details>
<details>
<summary>Tres</summary>
<div aria-label="Bueno, bueno, bueno">๐๐๐</div>
</details>
</div>
<div class=accordion lang=fr>
<details>
<summary>Un</summary>
<div aria-label="Tu gรจres">๐ค</div>
</details>
<details>
<summary>Deux</summary>
<div aria-label="Tu gรจres, tu gรจres">๐ค๐ค</div>
</details>
<details>
<summary>Trois</summary>
<div aria-label="Tu gรจres, tu gรจres, tu gรจres">๐ค๐ค๐ค</div>
</details>
</div>
</div>
The Javascript...
<script>
// JS is required, falls back to default details behaviour
const accordions = (_ => {
// Class used but could be data attribute or custom element
const accordionQuery = '.accordion';
const accordionClicked = event => {
const summary = event.target;
if (summary.tagName.toLowerCase() !== 'summary') return;
const currentDetails = summary.parentElement;
const accordion = currentDetails.closest(accordionQuery);
const allOpenDetails = accordion.querySelectorAll('details[open]');
for (const details of allOpenDetails) {
// But not the clicked summary
if (details === currentDetails) continue;
details.removeAttribute('open');
}
};
// Consider each group of details (individual accordian)
const accordions = document.querySelectorAll(accordionQuery);
for (const accordion of accordions) {
accordion.addEventListener('click', accordionClicked);
}
})();
</script>