0

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?

0

3 Answers 3

3

Heres a list of all the keycodes http://mikemurko.com/general/jquery-keycode-cheatsheet/
- Enter: 13 - Up: 38 - Down: 40 - Right: 39 - Left: 37

    $(document).keyup(function(e) {
        if (e.which === 38) {
          //up was pressed
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

0

Use keyCode like below :

$(document).on('keypress','your-element',function(e){
    if(e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40)
    console.log("Arrow key pressed");
})

Comments

-3

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;
}

}

3 Comments

The keys codes you provided are not correct
Up: 38 Down: 40 Right: 39 Left: 37
onkeypress can't detect arrow keys! use keydown instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.