Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!