In Javascript, how do I tell if a user is pressing two keys at the same time?
For example, I have drawn a circle in the middle of the screen. I want to move it up while
Javascript keyboard events fire on keypress and keydown, but don't contain the additional keymask info to determine if other keys are pressed at the same time.
Javascript has onkeydown, and onkeyup events. You can simple fiddle a bit onkeydown for left arrow, and fiddle another bit for the up arrow. On keyup, fiddle the respective bit back.
var leftPressed,
upPressed,
rightPressed,
downPressed;
var milli = 100;
window.addEventListener('onkeydown', function(e) {
switch(e.keycode) {
case 37: //left
leftPressed = true;
case 38: //up
upPressed = true;
case 39: //right
rightPressed = true;
case 40: //down
downPressed = true;
default:
break;
}
});
window.addEventListener('onkeyup', function(e) {
switch(e.keycode) {
case 37: //left
leftPressed = false;
case 38: //up
upPressed = false;
case 39: //right
rightPressed = false;
case 40: //down
downPressed = false;
default:
break;
}
});
function moveCircle() {
if(leftPressed && !rightPressed) {
// move left
}
if(rightPressed && !leftPressed) {
// move right
}
if(upPressed && !downPressed) {
// move up
}
if(downPressed && !upPressed) {
// move down
}
}
setInterval(moveCircle, milli);
Here is what you need to do conceptually (I guess this is called pseudo code):
Start with something like this:
var PIXEL_DELTA = 10; // Distance to move in pixels
var leftPressed = 0,
upPressed = 0,
downPressed = 0,
rightPressed = 0;
Then on every keydown
event, test if it the key pressed is left
, up
, etc and turn its variable from 0
to PIXEL_DELTA
.
On every keyup
event, run the same test and turn the correct variable back to 0
.
Then, in your moving code (real code): (This code adapted from Crescent Fresh's awesome example):
function move() {
var dot = document.getElementById('dot'),
deltaX = rightPressed - leftPressed,
deltaY = downPressed - upPressed;
if(deltaX) {
dot.style.left = (parseInt(dot.style.left, 10) || 0) + deltaX + 'px';
}
if (deltaY) {
dot.style.top = (parseInt(dot.style.top, 10) || 0) + deltaY + 'px';
}
}
The browser will (should) fire a separate keydown
/keyup
event for each key, even if they are "simultaneously" pressed.
Working Example
Crescent Fresh put together a full example on JSBin. Be sure to visit the editable version as well to play with the code.
Maybe you can do it by keeping track of keydown and keyup event for each key and you'll know if two keys are being held at the same time.
Sample pseudo-code:
var keydown = {};
function onkeydown(event) {
keydown[event.key] = true;
}
function onkeyup(event) {
keydown[event.key] = false;
}
// in some function at some other places
if (keydown['up'] && keydown['right']) {
move_diagonal('up', 'right');
}
elseif (keydown['up'] && keydown['left']) {
move_diagonal('up', 'left');
}
elseif .. blah blah