Nickolay K
Nickolay K

Reputation: 13

Make vanilla JS accordion auto close previous section

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

Answers (2)

yellowsir
yellowsir

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

AdamKniec
AdamKniec

Reputation: 1717

What have You tried so far ? If You didn't, try the following logic.

Before you give an element a activeclass - 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

Related Questions