0

Following a tutorial about game development with HTML5. And I can't figure out why this piece of code won't display the alert when I push the up key on my keyboard.

var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");

var keys = [];

window.addEventListener("keydown", function(e) {
  keys[e.keyCode] = true;
}, false);

window.addEventListener("keyup", function(e) {
  delete keys[e.keyCode]
}, false);

if (keys[38]) alert("yep");

The Chrome console clearly shows that keys[38] is true and typing if (keys[38]) alert("yep"); in the console displays the alert. I think I am missing a fundamental thing here (or being fundamentally stupid). I will be glad to provide more info in case there is no obvious mistake in the JS code.

Thanks!

Kudos
  • 1,084
  • 8
  • 21
Flip
  • 6,233
  • 7
  • 46
  • 75

2 Answers2

2

The if will be called right at the end of your tick. The listeners start firing once you've left that tick. Hence, there's no chance for the keys array to be set when the if is executed.

The only pieces of your code that will be called afterwards are two callbacks passed to keydown and keyup events. If you want to react to those events, your code should reside inside of those callbacks.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
1

You need to put your code (the alert) inside the event listener like so:

window.addEventListener("keydown", function(e) {
  if(e.keyCode == 38) {
    alert('BOOYAKA');
  }
}, false);
Ronen Cypis
  • 21,182
  • 1
  • 20
  • 25