5

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")
0

2 Answers 2

9

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Arrived too late :-) @JG73 This is exactly what you need to do btw !
3

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.