tone4407
tone4407

Reputation: 89

Vanilla JS Accordion

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');
  });
});

Upvotes: 0

Views: 550

Answers (2)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

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");
    }
  });
});

Upvotes: 0

IT goldman
IT goldman

Reputation: 19485

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');
  });
});

Upvotes: 1

Related Questions