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:
Then on every
keydownevent, test if it the key pressed isleft,up, etc and turn its variable from0toPIXEL_DELTA.On every
keyupevent, run the same test and turn the correct variable back to0.Then, in your moving code (real code): (This code adapted from Crescent Fresh’s awesome example):
The browser will (should) fire a separate
keydown/keyupevent 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.