Home > Blockchain >  Remove item form array but keep event listener
Remove item form array but keep event listener

Time:01-15

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

CodePudding user response:

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);
})
  •  Tags:  
  • Related