Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
How do I make my accordion/collapsible work with event delegation?

I want to create an accordion in my webshop's cart drawer but I can't find a way to fix my issue.

What is happening here is that I get the element but as soon as the drawer is re-rendered then my reference is lost. Because the DOM dynamically changes, I should not do it this way. Instead, I should use event delegation so that my code can still work even when things are re-rendered.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}
<button type="button" class="accordion">Expand me</button>
<div class="panel">
  <p>Text here...</p>
</div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Have an accordion container element that you attach the listener to. Then also cache the divs within each panel div. Use classes to specify whether each panel's information should be visible. Initially we set them all to display: none.

const accordion = document.querySelector('.accordion');
const add = document.querySelector('.add');

accordion.addEventListener('click', handleClick, false);
add.addEventListener('click', handleAdd, false);

function handleAdd() {
  const html = '<div class="panel"><button>Expand me: newPanel</button><div><p>New Panel</p></div></div>';
  accordion.insertAdjacentHTML('beforeend', html);
}

function handleClick(e) {
  const button = e.target;

  // Check to see if the element we clicked on was
  // the button
  if (button.nodeName === 'BUTTON') {

    // Find the closest panel ancestor
    const parent = button.closest('.panel');

    // Get all of the panels, even the ones newly added
    const panels = accordion.querySelectorAll('.panel div');

    // Remove all the `show` classes from the panels
    panels.forEach(panel => panel.classList.remove('show'));

    // And add `show` to the panels `div` which we previous hid
    parent.querySelector('div').classList.add('show');
  }
}
.panel div { display: none; }
.panel div.show { display: block; }
.add { margin-top: 1em; background-color: #44aa77; }
<div class="accordion">
  <div class="panel">
    <button>Expand me: one</button>
    <div><p>One</p></div>
  </div>
  <div class="panel">
    <button>Expand me: two</button>
    <div><p>Two</p></div>
  </div>
  <div class="panel">
    <button>Expand me: three</button>
    <div><p>Three</p></div>
   </div>
</div>
<button class="add">Add new panel</button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda