Here is an accordion whose ‘details’ elements are opened and closed using ‘maxHeight’. The expand/collapse animation is done by CSS.
HTML-Code:
<details name="learn-css">
<summary>Accordion Summary 1</summary>
<p>Accordion Content 1</p>
</details>
<details name="learn-css">
<summary>Accordion Summary 2</summary>
<p>Accordion Content 2</p>
</details>
<details name="learn-css">
<summary>Accordion Summary 3</summary>
<p>Accordion Content 3</p>
</details>
<div>
<p>Text</p>
</div>
CSS-Code:
details {
max-height: 2rem;
overflow: hidden;
background-color: #eee;
}
details > p {
margin-top: 0;
}
summary {
min-height: 2rem;
border-top: solid 1px #ccc;
background-color: #fff;
}
.expand {
overflow: hidden;
max-height: 10rem;
transition: max-height .5s ease-out;
}
.collapse {
overflow: hidden;
max-height: 2rem;
transition: max-height .5s ease-out;
}
JavaScript-Code:
document.querySelectorAll('summary').forEach(el => el.addEventListener('click', (event) => {
const details = event.target.parentElement;
const onAnimationEnd = cb => details.addEventListener(
"animationend", cb, { once: true }
);
details.classList.add('expand');
if (details.open) {
event.preventDefault();
details.classList.add('collapse');
onAnimationEnd(() => {
details.classList.remove('expand', 'collapse');
details.removeAttribute("open");
});
setTimeout(() => {
details.dispatchEvent(new Event('animationend'));
}, 500);
}
}
));
This code works as expected in the Firefox browser, but not in the Chrome browser. If one ‘details’ element is open and I click on another closed ‘details’ element to open it, the already open ‘details’ element closes automatically because the ‘open’ attribute is removed from this ‘details’ element. Actually, the ‘open’ attribute should remain on this ‘details’ element. The CSS animation then no longer works for this ‘details’ element because the CSS class ‘expand’ has not been removed. I thought that maybe the event bubbling was responsible for this and used ‘stopPropagation’. But that didn’t help.
Normally, the automatic closing of an open ‘details’ element when clicking on another closed ‘details’ element must be programmed separately. In my case, the automatic closing is an unwanted side effect in the Chrome browser.
gbecker is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.