Identicon Identicon - 2 months ago 9
Javascript Question

How to detect arrow key-presses in JavaScript?

I am making a car racing game in JavaScript. The car is controlled by the arrow keys. I have made a lot of games in JavaScript before and it worked.

The code I had used is:

function detectKey(e) {
var event = window.event ? window.event : e;
if (true) {
alert(event.keyCode)
}
}


Now I am using this code the first time for arrow keys. Whenever I press the arrow keys the the page is moving up and down. I am not understanding the problem. Can somebody help?

Answer

in pure JavaScript

document.onkeydown = function myFunction() {
switch (event.keyCode) {
case 38:
    console.log("Up key is pressed");
    break;
case 40:
    console.log("Down key is pressed");
    break;
case 37:
    console.log("Right key is pressed");
    break;
case 39:
    console.log("left key is pressed");
    break;
}

}

Comments