event.key === "ArrowRight"...
More recent and much cleaner: use event.key
. No more arbitrary number codes! If you are transpiling or know your users are all on modern browsers, use this!
node.addEventListener('keydown', function(event) {
const key = event.key; // "ArrowRight", "ArrowLeft", "ArrowUp", or "ArrowDown"
});
Verbose Handling:
switch (event.key) {
case "ArrowLeft":
// Left pressed
break;
case "ArrowRight":
// Right pressed
break;
case "ArrowUp":
// Up pressed
break;
case "ArrowDown":
// Down pressed
break;
}
Modern Switch Handling:
const callback = {
"ArrowLeft" : leftHandler,
"ArrowRight" : rightHandler,
"ArrowUp" : upHandler,
"ArrowDown" : downHandler,
}[event.key]
callback?.()
NOTE: The old properties (.keyCode
and .which
) are Deprecated.
"w", "a", "s", "d"
for direction, use event.code
To support users who are using non-qwerty/English keyboard layouts, you should instead use event.code
. This will preserve physical key location, even if resulting character changes.
event.key
would be , on Dvorak and z on Azerty, making your game unplayable.
const {code} = event
if (code === "KeyW") // KeyA, KeyS, KeyD
Optimally, you also allow key remapping, which benefits the player regardless of their situation.
P.S. event.code
is the same for arrows
key
Mozilla Docs
code
Mozilla Docs
Supported Browsers
keypress
events for arrow keys, but you're right thatkeydown
always works for arrow keys. – Iridic