How to overwrite event handler for 'click' event in javaScript?

Viewed 8877

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.

4 Answers

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);
Related