Detecting arrow key presses in JavaScript
Solution 1:
Arrow keys are only triggered by onkeydown
, not onkeypress
.
The keycodes are:
- left = 37
- up = 38
- right = 39
- down = 40
Solution 2:
On key up and down call function. There are different codes for each key.
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
}
else if (e.keyCode == '40') {
// down arrow
}
else if (e.keyCode == '37') {
// left arrow
}
else if (e.keyCode == '39') {
// right arrow
}
}
Solution 3:
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
Solution 4:
Possibly the tersest formulation:
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
alert('left');
break;
case 38:
alert('up');
break;
case 39:
alert('right');
break;
case 40:
alert('down');
break;
}
};
Demo (thanks to user Angus Grant): http://jsfiddle.net/angusgrant/E3tE6/
This should work cross-browser. Leave a comment if there is a browser where it does not work.
There are other ways to get the key code (e.which, e.charCode, and window.event instead of e), but they should not be necessary. You can try most of them out at http://www.asquare.net/javascript/tests/KeyCode.html. Note that event.keycode does not work with onkeypress in Firefox, but it does work with onkeydown.