The example for this question is http://jsfiddle.net/4ac5u/
var x = 0;
var y = 0;
$(document).keydown(function(e){
if (e.keyCode == 37) {
$("#left").css( "background-color", "red" );
x = x-1;
$("#ball").css( "margin-left", x*10 );
return false;
}
});
$(document).keyup(function(e){
if (e.keyCode == 37) {
$("#left").css( "background-color", "#fff" );
return false;
}
});
$(document).keydown(function(e){
if (e.keyCode == 38) {
$("#up").css( "background-color", "red" );
y = y-1;
$("#ball").css( "margin-top", y*10 );
return false;
}
});
$(document).keyup(function(e){
if (e.keyCode == 38) {
$("#up").css( "background-color", "#fff" );
return false;
}
});
$(document).keydown(function(e){
if (e.keyCode == 39) {
$("#right").css( "background-color", "red" );
x = x+1;
$("#ball").css( "margin-left", x*10 );
return false;
}
});
$(document).keyup(function(e){
if (e.keyCode == 39) {
$("#right").css( "background-color", "#fff" );
return false;
}
});
$(document).keydown(function(e){
if (e.keyCode == 40) {
$("#down").css( "background-color", "red" );
y = y+1;
$("#ball").css( "margin-top", y*10 );
return false;
}
});
$(document).keyup(function(e){
if (e.keyCode == 40) {
$("#down").css( "background-color", "#fff" );
return false;
}
});
In this example I have different Jquery keydown listeners waiting for a specific key press, and on that keypress I want to move a ball in a certain direction (in this example using the css function to change the margin).
The issue is that you can only move in one direction at a time. Is it possible to have it so that if I have the down arrow and the right arrow down at the same time I move towards the bottom left part of the screen, not just right or down?
I have thought about possibly finding a way to alternate between them if both are pressed, but I'm not sure how that would work. Or if there is some way to do threading.
Also I'm not sure if there is a way to also make it not cancel out on pressing a new button while you are still holding the other down.