Ad

Removing Event Listeners

- 1 answer

If I add an event handler to an event like

HTMLElement.onclick = somefunction;

How can I remove the event handler added in the above style.

I tried using removeEventListener like below, but it didn't work.

HTMLElement.removeEventListener('click', somefunction)

What can I do?

Ad

Answer

If you use the onclick assignment method, you need to re-assign onclick to a different value to "unbind" it, e.g.:

HTMLElement.onclick = null;

Please note though that using onclick is considered bad practice as it doesn't allow you to bind multiple functions, prefer addEventListener instead.

Ad
source: stackoverflow.com
Ad