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.