0

So I have this code running in a jsp file (in the body of the html):

<p id="left">LEFT: 0</p>
<p id="up">UP: 0</p>
<p id="right">RIGHT: 0</p>
<p id="down">DOWN: 0</p>
<script type="text/javascript">

var left = 0, right = 0; up = 0; down = 0;
document.onkeydown = function(evt) {
    evt = evt || window.event; //pour vieux IE
    switch (evt.keyCode) {
        case 37:
            leftArrowPressed();
            break;
        case 38:
            upArrowPressed();
            break;
        case 39:
            rightArrowPressed();
            break;
        case 40:
            downArrowPressed();
            break;
    }
};

function leftArrowPressed() {
    left++;
    document.getElementById("left").textContent = "LEFT: " + left;
}

function upArrowPressed() {
    up++;
    document.getElementById("up").textContent = "UP: " + up;
}

function rightArrowPressed() {
    right++;
    document.getElementById("right").textContent = "RIGHT: " + right;
}

function downArrowPressed() {
    down++;
    document.getElementById("down").textContent = "DOWN: " + down;
}

document.onkeyup = function(evt) {
    evt = evt || window.event; //pour vieux IE
    switch (evt.keyCode) {
        case 37:
            left = 0;
            document.getElementById("left").textContent = "LEFT: " + left;
            break;
        case 38:
            up = 0;
            document.getElementById("up").textContent = "UP: " + up;
            break;
        case 39:
            right = 0;
            document.getElementById("right").textContent = "RIGHT: " + right;
            break;
        case 40:
            down = 0;
            document.getElementById("down").textContent = "DOWN: " + down;
            break;
    }
};

It works in this sense: I press an arrow, a counter increment. when I release it, the counter gets back to 0.

The thing is to be able to press multiple arrows at the same time. Right now, if I hold left and then hold right after, the left won't increment but the right will. Is it possible that both increment at the same time?

Note: I've used this thread to help me with the arrow key pressing in Javascript: Detecting arrow key presses in JavaScript

Community
  • 1
  • 1
J. Doe
  • 3
  • 2
  • 2
    [Works fine for me](https://jsfiddle.net/terc23z3/). – Mike Cluck Jun 21 '16 at 17:02
  • If you press two keys at once, one will increment once, and the other will continue to increment. This action occurs because in reality you don't press both keys down at the exact same time. Which ever one you pressed down last will be the one to continously increment while the other will be stuck at one (till you release that key/keys) – kemicofa ghost Jun 21 '16 at 17:07
  • That and that's how a switch case works. It'll go to the first case and then exit. – EasyBB Jun 21 '16 at 17:08

0 Answers0