Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to remove all event handlers of a given element in javascript?

I would like to remove ALL handlers for a given event type. Let's say I've added twice "onclick event" to a button and now I would like to return back to the original state where no event handler was set to the button.

How can I do that?

P.S.: I've found removeEventListener (non-IE)/detachEvent (IE) methods but the functions want me to pass as a parameter the function that handles the event which seems to me quite clumsy because I would have to store the functions somewhere.

EDIT: http://ejohn.org/blog/flexible-javascript-events/ - I'm now using this code

like image 686
Martin Vseticka Avatar asked May 14 '10 20:05

Martin Vseticka


People also ask

Can event handlers be removed?

Go to the objects tab, view the Document object (don't click on edit) and scroll down to Event Handlers. Select the one to delete and press delete.

How do I remove all event listeners from an element?

To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.

Can you remove an event listener JavaScript?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.

How do you remove all click events JS?

If you want to remove all event handlers (of any type), you could clone the element and replace it with its clone: var clone = element. cloneNode(true);


2 Answers

It might be a good idea to use jQuery or a similar framework to manage all event handlers. This will give you easy-to-use, unobtrusive functions to add and remove event handlers:

$(...).on('click', function() { ... }); $(...).off('click'); // or, to unbind all events: $(...).off(); 
like image 83
ThiefMaster Avatar answered Sep 18 '22 02:09

ThiefMaster


If you have only one child element under your element's parent (or if you don't mind all sibling's event handlers lost too):

elem.parentElement.innerHTML = elem.parentElement.innerHTML; 

Tested in Chrome 49, FF 44, IE 11

It removes all 'addEventListener'-s.

like image 26
fenyoapa Avatar answered Sep 19 '22 02:09

fenyoapa