Home > Software design >  How can I remove an event listener in JavaScript?
How can I remove an event listener in JavaScript?

Time:03-19

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 >start</button>
    <button >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
            }
        })
    }

CodePudding user response:

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 >start</button>
<button >stop</button>


Removing keyboardControl doesn't work for a multiple reasons:

  • It's not actually the handler that you want to remove. The function adds another event handler, but removing it won't automagically remove the handler it added.
  • keyboardControl is never bound as an event handler to document.
  • Related