How can you remake this accordion script for a function so that it can be used several times on the site?

  • 0
    How can you modify this accordion script for a function so that it can be used several times on the site?
    let accordeonLink = document.querySelectorAll('.accordion-item__link'),
          accordeonItem = document.querySelectorAll('.accordion-item');
    
      accordeonLink.forEach((item) => 
        item.addEventListener('click',  () => {
          let parent = item.parentNode;
    
          if (parent.classList.contains('accordion-item__active')) {
            parent.classList.remove('accordion-item__active');
          } else {
            accordeonItem.forEach((child) => child.classList.remove('accordion-item__active'))
          }
    
          parent.classList.toggle('accordion-item__active');
    
        })
      );

    Or maybe someone has analogues?
    JavaScript Chloe Hoffman, Aug 30, 2020

  • 1 Answers
  • 0
    More or less like this. It's hard to guess without html.

    document.addEventListener('click', (event) => {
    let el = event.target //элемент по которому кликнули

    if (el.classList.contains('accordion-item__active')) {
    el.classList.remove('accordion-item__active');
    } else {
    document.querySelectorAll('.accordion-item__active').forEach(i => i.classList.remove('accordion-item__active'))
    }

    el.classList.toggle('accordion-item__active');

    })
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!