Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript unable to remove event listener with variable function

Hackcraft_

New Coder
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

JavaScript:
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.
 
Ok, just checking 😉 Then what is the result of the statement ? Did you get an error message in the console ?
You could also define a variable that you set true or false as needed, and have the event listener check for that variable (if true, just return). That's what I would do, instead of adding and removing the handler all the time.
 
Hi @Hackcraft_

I think you can use some flag to determine if the game is already started and based on that you can run the startGame function.
Your function might look something like this:

JavaScript:
const startGameOnEnter = function (event) {
  if (event.key === 'Enter' && !isGameRunning) {
    startGame()
    isGameRunning = true;
  }
}
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom