I'm currently trying to remove an event listener on click on a button (see code below) but it never works, I know I'm supposed to use the same function to cancel the event (here keyboardControl) but it doesn't seem to be working at all. Thanks in advance
<button class="start">start</button>
<button class="stop">stop</button>
const start = document.querySelector(".start")
const stopbtn = document.querySelector(".stop")
start.addEventListener("click", () => keyboardControl())
stopbtn.addEventListener("click", () => {
document.removeEventListener("keydown", keyboardControl)
})
function keyboardControl() {
document.addEventListener("keydown", (e) => {
switch(e.keyCode) {
case 37: //left arrow key
console.log("left")
break
case 39:
console.log("right")
break
}
})
}
You have to pass the same function to removeEventListener that you passed to addEventListener. The function you are passing to addEventListener is
(e) => {
switch(e.keyCode) {
case 37: //left arrow key
console.log("left")
break
case 39:
console.log("right")
break
}
}
Since you are not storing a reference to it anywhere you cannot remove it. Assign that function to variable and use that to add and remove it:
const start = document.querySelector(".start")
const stopbtn = document.querySelector(".stop")
function handleKey(e) {
switch (e.keyCode) {
case 37: //left arrow key
console.log("left")
break
case 39:
console.log("right")
break
}
}
function keyboardControl() {
document.addEventListener("keydown", handleKey);
}
start.addEventListener("click", () => keyboardControl())
stopbtn.addEventListener(
"click",
() => document.removeEventListener("keydown", handleKey)
)
<button class="start">start</button>
<button class="stop">stop</button>
Removing keyboardControl doesn't work for a multiple reasons:
keyboardControl is never bound as an event handler to document.