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

140
Visualizações
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 Respostas
Responde à pergunta

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 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