JavaScript move delay and multiple keystrokes
javascript, keycode
Solution
First, to avoid the keypress/repeat delay, you have to wrap your program in a loop, and make the state of the keyboard available inside the scope of that loop, secondly to monitor multiple keypresses you need to keep track of individual keydown and keyup events:
var x = 0;
var y = 0;
// store the current pressed keys in an array
var keys = [];
// if the pressed key is 38 (w) then keys[38] will be true
// keys [38] will remain true untill the key is released (below)
// the same is true for any other key, we can now detect multiple
// keypresses
$(document).keydown(function (e) {
keys[e.keyCode] = true;
});
$(document).keyup(function (e) {
delete keys[e.keyCode];
});
// we use this function to call our mainLoop function every 200ms
// so we are not relying on the key events to move our square
setInterval( mainLoop , 200 );
function mainLoop() {
// here we query the array for each keyCode and execute the required actions
if(keys[37]){
x -= 10;
$("#square").css("left", x);
}
if(keys[39]){
x += 10;
$("#square").css("left", x);
}
if(keys[38]){
y -= 10;
$("#square").css("top", y);
}
if(keys[40]){
y += 10;
$("#square").css("top", y);
}
}
Problem
Here is my problem: http://testepi.kvalitne.cz/test/ I do not want the delay between a keypress and the movement of the square. I would also like to know how to move diagonally (pressing two keys at same time). My code: ``` $(function(){ document.addEventListener("keydown", move, false); var x = 0; var y = 0; function move(event){ if(event.keyCode==37){ x -= 10; $("#square").css("left", x); } if(event.keyCode==39){ x += 10; $("#square").css("left", x); } if(event.keyCode==38){ y -= 10; $("#square").css("top", y); } if(event.keyCode==40){ y += 10; $("#square").css("top", y); } } }); ```