Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
Keeping events alive Since we only need the listener for our modal, it should be removed whenever the user cannot interact with our modal any longer. The same is true for any element that can be toggled as well as animations on elements.
To do this without any libraries:
document.getElementById("aspnetForm").onsubmit = null;
With jQuery
$('#aspnetForm').unbind('submit');
And then proceed to add your own.
Try this, this is working for me:
$('#aspnetForm').removeAttr('onsubmit').submit(function() {
alert("My new submit function justexecuted!");
});
See this for more details.
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()"
.
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