How do I remove a event listener?

I made a game with a simple menu, and now wish that the player can simply press enter to start the game instead of having to click the start button every time. however, I don’t want the function to be active during the gameplay. This is my current code

const startGameOnEnter = function (event) {

  console.log(event.key)

  if (event.key === 'Enter') {

    startGame()

    removeEventListener('keydown', startGameOnEnter.bind(KeyboardEvent))

    }

}



addEventListener('keydown', startGameOnEnter.bind(KeyboardEvent))

The function works, however, it cannot successfully remove the event listener.

bind returns a new bound function each time so the listener is different. You can create the bound function and save it to a variable and use that for the add/remove callback.

const boundFn = handleClick.bind(this);

function handleClick() {
  click.removeEventListener("click", boundFn);
}

click.addEventListener("click", boundFn);

Or you can use the options object with once set to true. That way the listener is removed after calling the handler (you do not need removeEventListener at all).

click.addEventListener("click", handleClick.bind(this), { once: true });