Can someone help me implement removeEventListener? I have multiple event listeners and I want to to make it so when one is clicked the others are removed, however my current removeEventListener is not working… Please see code below.
playerDiscard() {
//if player card x is clicked run the click event
playerCardSlot1.addEventListener('click', () => this.clickHandler(), {once:true});
playerCardSlot2.addEventListener('click', () => this.clickHandler2(), {once:true});
playerCardSlot3.addEventListener('click', () => this.clickHandler3(), {once:true});
playerCardSlot4.addEventListener('click', () => this.clickHandler4(), {once:true});
playerCardSlot5.addEventListener('click', () => this.clickHandler5(), {once:true});
}
now if one clickEvent is ran how do I remove the other 4?
I am using once option, but that is not my issue. I am not sure if you looked at my code, but I just need to remove other event listeners once one has been clicked. However, my trouble is that if I do something like playerCardSlot1.addEventListener('click', this.clickHandler, {once:true}); i get an HTMLDivError saying this.stopAnimation and this.playHand are not functions in the scope. Not really sure how to tackle this…
We have to see more of the code to know the context. Post a link to a GitHub or a live version on something like Codepen.
Looking at the method names and some of the other code it just doesn’t look like you are doing this correctly. It’s highly unlikely that you actually want multiple clickHandler methods on separate elements. More likely you want one method with some logic inside it and targeting the click target (and/or doing DOM traversal). Inside the single handleClick method you then can remove all the other event listeners after the logic by just looping the collection of elements.