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
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.
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.
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.
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);
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With