Home > Net >  Vanilla JS Accordion
Vanilla JS Accordion

Time:07-01

Given the code below, how can I add functionality that hides active items when clicking on another? I'd like only one item to be open at a time.

const toggleElements = document.querySelectorAll('.accordion__item');

toggleElements.forEach(el => {
  el.addEventListener('click', function() {
    this.classList.toggle('is-active');
  });
});

CodePudding user response:

Close all others, then open current.

const toggleElements = document.querySelectorAll('.accordion__item');

toggleElements.forEach(el => {
  el.addEventListener('click', function() {
    toggleElements.forEach(el => el.classList.remove('is-active'));
    this.classList.add('is-active');
  });
});

CodePudding user response:

inline comments

toggleElements.forEach((el) => {
  el.addEventListener("click", function () {
    // check whether already active or not
    const isActive = this.classList.contains("is-active");

    // reset to collapse all including the current item
    toggleElements.forEach((el) => el.classList.remove("is-active"));

    // if collapsing from expand, it is already in above loop

    // if intended to expand (from collapse)
    if (!isActive) {
      this.classList.add("is-active");
    }
  });
});
  • Related