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?

Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67

3 Answers3

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
        }
    });
NickOS
  • 764
  • 1
  • 7
  • 18
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");
})
Rav's Patel
  • 743
  • 6
  • 22
-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;
}

}

Sunil B N
  • 4,159
  • 1
  • 31
  • 52