How to Clear/Remove JavaScript Event Handler?

JavascriptHtmlDom Events

Javascript Problem Overview


Given the following HTML fragment:

<form id="aspnetForm" onsubmit="alert('On Submit Run!'); return true;">

I need to remove/clear the handler for the onsubmit event and register my own using jQuery or any other flavor of JavaScript usage.

Javascript Solutions


Solution 1 - Javascript

To do this without any libraries:

document.getElementById("aspnetForm").onsubmit = null;

Solution 2 - Javascript

With jQuery

$('#aspnetForm').unbind('submit');

And then proceed to add your own.

Solution 3 - Javascript

Try this, this is working for me:

$('#aspnetForm').removeAttr('onsubmit').submit(function() {   
    alert("My new submit function justexecuted!"); 
});

See this for more details.

Solution 4 - Javascript

This is an ancient question now, but given that the major browsers have all abandoned EventTarget.getEventListeners(), here's a way to remove ALL event handlers on the element and its children and retain only the HTML structure. We simply clone the element and replace it:

let e = document.querySelector('selector');
let clone = e.cloneNode(true);
e.replaceWith(clone);

This is just as much of a hack as preempting the addEventListener() prototype with a method that keeps track of every handler function, but at least this can be used after the DOM is already wired up with another script's events.

This also works about the same as above using jQuery's clone() instead of cloneNode():

let original = $('#my-div');
let clone = original.clone();
original.replaceWith(clone);

This pattern will effectively leave no event handlers on the element or its child nodes unless they were defined with an "on" attribute like onclick="foo()".

Solution 5 - Javascript

For jQuery, off() removes all event handlers added by jQuery from it.

$('#aspnetForm').off();

> Calling .off() with no arguments removes all handlers attached to the elements.

Solution 6 - Javascript

For jQuery, if you are binding event handlers with .live, you can use .die to unbind all instances that were bound with .live.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJordan TerrellView Question on Stackoverflow
Solution 1 - JavascriptjiggyView Answer on Stackoverflow
Solution 2 - JavascriptPeter BaileyView Answer on Stackoverflow
Solution 3 - JavascriptRyanView Answer on Stackoverflow
Solution 4 - JavascriptAakashView Answer on Stackoverflow
Solution 5 - JavascriptzwcloudView Answer on Stackoverflow
Solution 6 - JavascriptBrian DiCasaView Answer on Stackoverflow