How do I detect when one of the arrow keys are pressed? I used this to find out:
function checkKey(e) {
var event = window.event ? window.event : e;
console.log(event.keyCode)
}
Though it worked for every other key, it didn't for arrow keys (maybe because the browser is supposed to scroll on these keys by default).
This library rocks! https://craig.is/killing/mice
You need to press the sequence a bit fast to highlight the code in that page though.
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!Verbose Handling:
You can easily extend this to check for
"w", "a", "s", "d"
, or any other keyMozilla Docs
Supported Browsers
P.S.
event.code
is the same for arrowsHere's an example implementation:
arrow keys are only triggered by
onkeydown
, notonkeypress
keycodes are:
Use
keydown
, notkeypress
for non-printable keys such as arrow keys:The best JavaScript key event reference I've found (beating the pants off quirksmode, for example) is here: http://unixpapa.com/js/key.html
Modern answer since keyCode is now deprecated in favor of key: