Skip to content
Advertisement

javascript remove “onclick” event listener

I have tried many things, but none of them work. I wonder if it’s impossible? I know the ‘normal’ way with ‘bind’, but the arrow functions are much more readable and I prefer to use them.

To better understand my question I made this sample code that illustrates the problem as fully as possible.

JavaScript
JavaScript

Advertisement

Answer

Because you didn’t add the listener using addEventListener, removeEventListener won’t work – to remove a listener attached by assigning to onclick, simply assign null to the onclick property again:

JavaScript

JavaScript
JavaScript

If you did use addEventListener, then to use removeEventListener later, you would have to have a reference to the same function you passed in to addEventListener originally, such as with

JavaScript

and then

JavaScript

JavaScript
JavaScript
Advertisement