Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keys pressed at the same time

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?

like image 437
Mageek Avatar asked Dec 13 '22 00:12

Mageek


1 Answers

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/

like image 136
Naftali Avatar answered Dec 22 '22 10:12

Naftali