Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
remove eventListener from for loop

I'm trying to remove the event listener that I've added in for loop but it didn't work

Is there a way to do this with pure js?

for (let i = 0; i < drumPads.length; i++) {
    drumPads[i].addEventListener("click", func)
    function func() {
      display.innerHTML = music[i][0];
      sound.src = music[i][1];
      sound.play();
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your function func should be defined outside the loop.

In your code the function func is block scoped and hence this wont be refering to the same memory when the user enters with "on" and "off" condition.

You can pass the index and some custom data from the target to the listner function by setting dataset of the target.

let drumPads = document.getElementsByClassName("drum-pads");

function Power(a) {
  for (let i = 0; i < drumPads.length; i++) {
    if (a === 'on') {
      drumPads[i].dataset.index = i;
      drumPads[i].addEventListener("click", func);
    } else {
      drumPads[i].removeEventListener("click", func);
    }
  }
}

function func(e) {
  const targetIndex = e.currentTarget.dataset.index;
  console.log('Triggered listner', targetIndex);
}
<div>
  <button class="drum-pads">drum-pads 1</button>
  <button class="drum-pads">drum-pads 2</button>
  <button class="drum-pads">drum-pads 3</button>
  <button class="drum-pads">drum-pads 4</button>
</div>
<div>
  <button onclick="Power('on')">Toggle On</button>
  <button onclick="Power('off')">Toggle Off</button>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda