Reputation: 91
First, I would like to thank all for your help and replies.
I'm working on a project that required users to press a key and hold it, it will trigger an action.
When the user presses another key ( still holing the first key), it will trigger another action.
However, I'm stuck getting JavaScript to recognize two keys being pressed at the same time.
var down = false;
var keys;
document.addEventListener("keydown", function (e) {
if (down) {return;}
down = true;
keys = (keys || []);
keys[e.keyCode]=true;
if (keys[87]){
console.log("1");
}
else if (keys[83]){
console.log("2");
}
else if (keys[83] && keys[87]){
console.log("sucessfull");
}
} , false);
document.addEventListener("keyup", function (e) {
down = false;
keys[e.keyCode]=false;
stop();
}, false);
<button id="up" onmousedown="Drive(1)" onmouseup="Drive(2)">UP </button>
Upvotes: 1
Views: 6024
Reputation: 1207
Got rid of the else branching as it would be satisfied (by 87 or 83) before ever getting to the && condition
var keys;
document.addEventListener("keydown", function (e) {
keys = (keys || []);
keys[e.keyCode]=true;
if (keys[87]){
console.log("1");
}
if (keys[83]){
console.log("2");
}
if (keys[83] && keys[87]){
console.log("sucessfull");
}
} , false);
document.addEventListener("keyup", function (e) {
keys[e.keyCode]=false;
stop();
}, false);
Upvotes: 3