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.
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).