I have accordion widget on my static HTML/CSS/JS site.
By default all accordions are closed.
User can open any of them and those will stay opened until the user manually closes them by clicking on the accordion title.
How can I make previously opened accordions to close when users click to open another one?
I created my accordion using this template: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_accordion_animate
I put both HTML and JS in the HTML file:
var acc = document.getElementsByClassName(accordion);
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener(click, function() {
this.classList.toggle(active);
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + px;
}
});
}
.accordion {
color: #fff;
background-color: #00000042;
cursor: pointer;
padding: 10px 10px;
margin-top:20px;
width: 100%;
border: 1px solid #00000042;
text-align: left;
outline: none;
transition: 0.4s;
}
.active, .accordion:hover {
background-color: #00000042;
border: 1px solid #fc8e2d;
}
.panel {
padding: 0 18px;
font-size: 18px;
background-color: #00000042;
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease-out;
}
<button class=accordion><span class=faq__question-heading>Title1</span></button>
<div class=panel>
<p style=padding:18px 0;>description1</p>
</div>
<button class=accordion><span class=faq__question-heading>Title2</span></button>
<div class=panel>
<p style=padding:18px 0;>description2</p>
</div>
<button class=accordion><span class=faq__question-heading>Title3</span></button>
<div class=panel>
<p style=padding:18px 0;>description3</p>
</div>
<script>
</script>