admin管理员组

文章数量:1220831

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.

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.

Share Improve this question asked Mar 19, 2016 at 18:08 Neha GuptaNeha Gupta 1,0675 gold badges18 silver badges36 bronze badges 1
  • You are passing different functions to addEventListener and removeEventListener. That can't work. – Felix Kling Commented Mar 19, 2016 at 18:13
Add a comment  | 

4 Answers 4

Reset to default 6

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 */

As you can see from some other answers, removing an event listener can be kind of a nightmare. Thankfully in certain circumstances there is an easier way: add another event listener that fires earlier and cancels out the rest.

In my case there was a click event handler I wanted to override and I was able to add another event handler with useCapture=true (among other things) to override it.

document.body.addEventListener('click',function (e) {
  if (e.target.innerHTML.toLowerCase() == 'regular') {
    e.target.insertAdjacentHTML('afterend','<div>One we do <strong>not want</strong></div>');
    e.preventDefault();
  }
});
document.body.addEventListener('click',function (e) {
  if (e.target.innerHTML.toLowerCase() == 'fixed') {//or any event or other pre-/evaluations/conditions here
    e.target.insertAdjacentHTML('afterend','<div>One we <strong>do want</strong></div>');
    e.preventDefault();
    e.stopPropagation();
  }
  //document.querySelector('.somethingelse').click();//etc.
},true);
<div><a href="#">Regular</a></div>
<div><a href="#">Fixed</a></div>

I was building a chrome extension and for some reason removeEventListener was not working as expected. The solution I came up with was to use the cloneNode method.

The documentation says

Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties.

What I did was created a clone for my actual element and replaced it with the cloned one. This removes all event listeners from the element. A simple example will be like

let newClonedElem = myActualElem.cloneNode(true);
myActualElem.parentNode.replaceChild(newClonedElem, myActualElem);

本文标签: How to overwrite event handler for 39click39 event in javaScriptStack Overflow