I want to overwrite event handler for click event. This is the event handler I have attached initially.
document.querySelector("[data-id='start-btn']")
.addEventListener("click", function (evt) {
//some code
});
Again after some condition, I want to over write this handler and attach new for 'click' event.
//removing
document.querySelector("[data-id='start-btn']")
.removeEventListener("click", function (evt) {
//some code
}, false);
//attaching new
document.querySelector("[data-id='start-btn']")
.addEventListener("click", function (evt) {
//code
});
But still it is executing the previous event handler.I have used removeEventListener(but I guess, its not working).
Guide me where I am going wrong.
Note: The addEventListener() method can have multiple event handlers applied to the same element. It doesn't overwrite other event handlers. Example: Below is a JavaScript code to show that multiple events are associated with an element and there is no overwriting.
addEventListener does not overwrite existing event listeners, it simply adds a new one as the method name implies. Existing listeners must be removed using the removeEventListener method.
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.
Clear the handlerTo remove an event handler, you can't just delete handler code that is in the form's code-behind file, it's still referenced by the event.
The only way to remove a handler added with addEventListener
is to use removeEventListener
with exactly the same arguments. That means you'll need a reference to the original function:
var handler = function (evt) {
//some code
};
document.querySelector("[data-id='start-btn']").addEventListener("click", handler);
then to remove
document.querySelector("[data-id='start-btn']").removeEventListener("click", handler);
removeEventListener
makes sense really only when using function references rather than passing an entire function body to both it and addEventListener
, which would potentially mean mass duplication of code (and, as you've found, doesn't work anyway.)
So, prepare a reference to your function:
function my_func() { /* code */ }
And pass it as the handler argument to add/removeEventListener
document.querySelector('query').addEventListener('click', my_func);
document.querySelector('query').removeEventListener('click', my_func);
There is an easier way that utilises an older coding standard. If you specifically want only one event handler for a given type and element, you can use the DOM-zero onclick
.
document.querySelector('query').onClick = my_func;
document.querySelector('query').onClick = my_func2; /* my_func() will no longer fire */
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