Reputation: 13
I found this great accordion with a very compact code but what I miss here is a function to auto close previous section when opened another one. It's probably quite easy but I'm a complete JS noob, sadly. Original code source.
const items = document.querySelectorAll(".accordion a");
function toggleAccordion(){
this.classList.toggle('active');
this.nextElementSibling.classList.toggle('active');
}
items.forEach(item => item.addEventListener('click', toggleAccordion));
Upvotes: 1
Views: 967
Reputation: 939
you could store the active one...
const items = document.querySelectorAll(".accordion a");
let active = null;
function toggleAccordion(){
if(active){
active.classList.toggle('active');
}
this.classList.toggle('active');
this.nextElementSibling.classList.toggle('active');
active = this;
}
items.forEach(item => item.addEventListener('click', toggleAccordion));
Upvotes: 0
Reputation: 1717
What have You tried so far ? If You didn't, try the following logic.
Before you give an element a active
class - loop over the rest of the elements and remove it from all of them :)
const items = document.querySelectorAll(".accordion a");
const remove = () => {
items.forEach(el => {
el.classList.remove('active');
el.nextElementSibling.classList.remove('active');
})
}
function toggleAccordion(){
remove()
this.classList.toggle('active');
this.nextElementSibling.classList.toggle('active');
}
items.forEach(item => item.addEventListener('click', toggleAccordion));
Upvotes: 1