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

135
Vistas
Remove item form array but keep event listener

I have an array of items to which I have appended the same event listener, and I need to drop a specific item from the array, but I'd like to keep the event listener on it.

Of course I could add it separately, but I was wondering if there was an easy way.

Here is a pen to show that. The function that is supposed to remove the focus from the buttons after some time does not execute on the third button.

Here is the JavaScript for more clearness:

const buttons = [...document.querySelectorAll(".button")];
let dropButton;

for (let i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener("click", function () {
        setTimeout(() => { buttons[i].blur(); }, 500);
    });
    
    if(buttons[i].classList.contains("drop")) {
        dropButton = buttons.splice(i, 1);
        i--;
    }
}

Thanks for your help :)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The event listener does keep connected, but when pressing the "dropped" button, the handler will blur the wrong button. This is because your handler accesses the buttons[i] by an index that is not valid anymore.

These are three other solutions that may be possible for your handler:

  // assigning the button to a closure scoped constant
  const b = buttons[i];
  buttons[i].addEventListener("click", function () {
    setTimeout(() => {b.blur();}, 500);
  })

or

// the "this" context in the handler is the button
buttons[i].addEventListener("click", function () {
  setTimeout(() => { this.blur();}, 500);
})

or

// the handler get and event whose "target" key is the button
buttons[i].addEventListener("click", function (event) {
   setTimeout(() => {event.target.blur();}, 500);
})
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