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>