I am having some difficulty using using an accordion in HTML & JS. I am trying to code it so only one accordion is open at a time. If someone clicks and opens a new accordion, all the other should close. This my HTML.
<div class="accordion">
<div class="accordion-item">
<div class="accordion-item-header">
HUMBER RADIO
</div>
<div class="accordion-item-body">
<div class="accordion-item-body-content">
<ul>
<li><a href="">RADIO NEWS</a></li>
<li><a href="">PODCAST</a></li>
<li><a href="">CONTENT</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="accordion">
<div class="accordion-item">
<div class="accordion-item-header">
TV NEWS
</div>
<div class="accordion-item-body">
<div class="accordion-item-body-content">
<ul>
<li><a href="">COVID UPDATES</a></li>
<li><a href="">NORTH CAMPUS NEWS</a></li>
<li><a href="">LAKESHORE CAMPUS NEWS</a></li>
</ul>
</div>
</div>
</div>
</div>
Here is the JavaScript for the code. It can open all of them, but I am struggling to program it so the others close.
window.onload = pageReady;
function pageReady() {
const accordionItemHeaders = document.querySelectorAll(".accordion-item-header");
accordionItemHeaders.forEach(accordionItemHeader => {
accordionItemHeader.addEventListener("click", event => {
accordionItemHeader.classList.toggle("active");
const accordionItemBody = accordionItemHeader.nextElementSibling;
if(accordionItemHeader.classList.contains("active")) {
accordionItemBody.style.maxHeight = "100px";
}
else {
accordionItemBody.style.maxHeight = "0px";
}
});
});
}