document.removeEventListener javascript

Viewed 4547

How can I remove this type of listener?

document.addEventListener("onSomething", function(){
  //Do something
});

when try to remove return number argument exception, way a function in second parameter but i not have a function.

 document.removeEventListener("customUploadComplete")
2 Answers

You need to make a reference to the function in order to remove it. So pull it out into a function so you can remove it.

var thisThing = function(){
  //Do something
}

document.addEventListener("onSomething", thisThing);
document.removeEventListener("onSomething", thisThing);

You need to declare a function in order to remove it. This is because you need to reference it upon removal so that the browser can recognize which event to remove.

This will not work:

btn.addEventListener("click", function() { alert("clicked") });
btn.removeEventListener("click", function() { alert("clicked") });

because there is no reference to the function. Each function is unique, even if they have the same code within them.

If you declare a function you can store a reference to that function, and then remove it:

function clickEvent() {
  alert("clicked!");
}
btn.addEventListener("click", clickEvent);
btn.removeEventListener("click", clickEvent);

Here's an example:

let $ = document.querySelector.bind(document),
  btn = $("#b1"),
  add = $("#b2"),
  remove = $("#b3");

function clickEvent() {
  alert("click");
}

btn.addEventListener("click", clickEvent);

remove.addEventListener("click", function() {
  btn.removeEventListener("click", clickEvent);
   alert("event removed!");
});

add.addEventListener("click", function() {
  btn.addEventListener("click", clickEvent);
  alert("event added!");
});
<button id="b1">click me</button>
<p/>
<button id="b2">Add Event Listener</button> <button id="b3">Remove Event Listener</button>

Related