Search code examples
javascriptfunctionif-statementeventslistener

How to remove an event listener from window?


Im building a snake game and need to remove an event listener after the space bar has fired, but im not getting any luck as the following code;

window.removeEventListener('keypress', (event) 

doesn't do anything. Any ideas what is the proper way for this? Thanks

window.addEventListener('keypress', (event) => {
  console.log(event)
  if (event.key === ' ') {
    startGame()
    window.removeEventListener('keypress', (event))
  }
})

Solution

  • You need a reference to the function in order to remove it. Don't use anonymous functions, instead:

    function handleKeyPress(event){
      console.log(event)
      if (event.key === ' ') {
        startGame()
        window.removeEventListener('keypress', (event))
      }
    })
    
    //add it
    window.addEventListener('keypress',handleKeyPress);
    //remove it
    window.removeEventListener('keypress',handleKeyPress);