I'm looking for a key listener for a game I'm developing in JavaScript. I have no idea how this would work in real code but it would be somthing like this.
if(keyPress=upKey)
{
playerSpriteX+=10;
}
else if(keyPress=downKey)
{
playerSpriteY-=10;
}
ect...
I searched it up, and Google came up with things that involved AJAX which I don't understand yet. Is there a built in function in javascript that does this?
The code is
This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)
A bit more readable comparing is done by casting
event.key
to upper case (I used onkeyup - needed the event to fire once upon each key tap):Each key has it's own code, get it out by outputting value of "key" variable (eg for arrow up key it will be 'ARROWUP' - (casted to uppercase))
JSFIDDLE DEMO
If you don't want the event to be continuous (if you want the user to have to release the key each time), change
onkeydown
toonkeyup
FIDDLE
Did you check the small Mousetrap library?
Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.