Detecting arrow key presses in JavaScript
Detect arrow keys in JavaScript by responding to the keydown
event. Use the event.key
property for readable code:
Embed this listener on the document
to catch arrow key actions globally in your application.
Key events explained
Key events are triggered when a key is pressed. For arrow keys detection, you need keydown
and keyup
because these keys are non-printable and don't register a keypress
. event.key
returns a string which identifies the pressed key, simplifying the code compared to older keyCode
or charCode
properties.
The legacy and browser compatibility
The deprecated event.keyCode
and event.which
are still seen in legacy code. Here's how you can maintain cross-browser compatibility:
This way you'll account for older browsers not supporting event.key
.
Keyboard layouts and internationalization
Be mindful, key codes depend on keyboard layouts. For internationalization purposes, event.code
helps by providing the physical key pressed, regardless of keyboard layout.
Controlling browser's default actions
Browser's default actions to arrow keys, such as scrolling, might need overriding:
Implement preventDefault()
to block any default behavior and trigger your code instead.
Streamlined handling with switch-statements
Easily manage multiple keys with a switch statement instead of if-else chains:
This structure is not only scalable but also pleasingly maintainable.
Was this article helpful?