Can I know the number of keys pressed at the same time in Javascript?
If so, how can I have an array of their keyCode
?
You can listen for keydown and keyup events.
var keys = { length: 0 };
document.onkeydown = function(e){
if(!keys[e.keyCode]) {
keys[e.keyCode] = true;
keys.length++;
}
}
document.onkeyup = function(e){
if(keys[e.keyCode]) {
keys[e.keyCode] = false;
keys.length--;
}
}
Then all the keys that are true
are the ones that are pressed currently.
Fiddle demo thanks to @Esailija: http://jsfiddle.net/maniator/Gc54D/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With