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.
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.
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