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 the user holds down the up arrow and right while the user holds down the right arrow. That part works easy. If user holds both the up and right arrows, I want to move the circle diagonally, up and to the right.
It doesn't look like this possible with basic Javascript event handling, but surely someone has figured out a work around/hack/improvement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With