0

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

2
  • Well the third button is no longer inside the buttons array, have you considered using this inside the event function to achieve the blur? Commented Jan 14, 2022 at 14:49
  • No, I didn't. Thanks! Commented Jan 14, 2022 at 15:57

1 Answer 1

2

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);
})
Sign up to request clarification or add additional context in comments.

1 Comment

Clear and simple, thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.