Search code examples
javascriptaddeventlistenerkeycode

I want a right arrow to change variable, but it will not work


When I hit the right arrow, it does not change the variable. Here's my code:

var squareX = 10;
document.addEventListener("keypress", function(e) {
  if (e.keyCode === 39) {
    squareX += 10;
  }
});

Solution

  • Use keydown instead of keypress:

    document.addEventListener("keydown", function(e) {
        if (e.keyCode === 39) {
           squareX += 10;
        }
    });
    

    That did the trick for me!