user1176058
user1176058

Reputation: 676

Removing event listeners

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?

Upvotes: 1

Views: 82

Answers (2)

lleaff
lleaff

Reputation: 4309

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.

Upvotes: 5

Richard Hamilton
Richard Hamilton

Reputation: 26434

Use addEventListener with removeEventListener

Example

HTMLElement.addEventListener('click', somefunction)
HTMLElement.removeEventListener('click', somefunction)

Upvotes: 2

Related Questions