Identicon Identicon - 8 months ago 40
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) {

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?


in pure JavaScript

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