Home > Net >  Can't call function within keyDown or keyPress event handlers
Can't call function within keyDown or keyPress event handlers

Time:01-28

Can't call function within keyDown or keyPress event handlers.

 var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];

$(document).on("keydown",  nextSequence);

function nextSequence() {
   var randomNum = Math.floor(Math.random() * 4);
   var randomChosenColor = buttonColors[randomNum];
   return gamePattern.push(randomChosenColor);
}

CodePudding user response:

You probably don't need the return since your variable is scoped outside of the callback. As @Samathingamajig pointed out it's actually working. You can also call the keydown shorthand version with

$(document).keydown(function () {
    var randomNum = Math.floor(Math.random() * 4);
    var randomChosenColor = buttonColors[randomNum];
    gamePattern.push(randomChosenColor);
    // Check the current state of gamePattern
    console.log(gamePattern);

});
  •  Tags:  
  • Related