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