Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Checking Keyboard State

I am working on making a simple Javascript game and need to be able to check if certain keys are being pressed. I have tried binding to the onkeydown event, but the problem that I am having is twofold: first, it won't let me check to see if more than one key is being pressed at any time. And second, it pauses after holding the key down before it starts spamming the event.

In my code, I could either have an event, or a function that checks every millisecond to see if the key is being pressed. Seeing as this is a game, I would really have no problem with either.

like image 970
Ty Overby Avatar asked Dec 13 '10 08:12

Ty Overby


1 Answers

You can use onkeydown and onkeyup together:

var pressed={};
element.onkeydown=function(e){
     e = e || window.event;
     pressed[e.keyCode] = true;
}

element.onkeyup=function(e){
     e = e || window.event;
     delete pressed[e.keyCode];
}

with this code you store every pressed key code in the pressed variable and then you delete it when the key is released. So when you need to know which keys are pressed you can loop with a for(..in..) through the pressed object.

like image 68
mck89 Avatar answered Oct 11 '22 13:10

mck89