Explain Codes LogoExplain Codes Logo

Detecting arrow key presses in JavaScript

javascript
key-events
browser-compatibility
default-actions
Nikita BarsukovbyNikita Barsukov·Aug 6, 2024
TLDR

Detect arrow keys in JavaScript by responding to the keydown event. Use the event.key property for readable code:

document.addEventListener('keydown', (event) => { const key = event.key; switch (key) { case 'ArrowUp': console.log('Up arrow key pressed!'); break; case 'ArrowDown': console.log('Down arrow key pressed!'); break; case 'ArrowLeft': console.log('Left arrow key pressed!'); break; case 'ArrowRight': console.log('Right arrow key pressed!'); break; } });

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:

document.addEventListener('keydown', function(event) { var key = event.key || event.keyCode; if(key === 'ArrowUp' || key === 38) { // Up arrow key press magic happens here! 🎩✨ } // ... Handle other arrow keys as per needed });

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.

document.addEventListener('keydown', function(event) { if(event.code === 'ArrowUp') { // Global citizen's response to physical ArrowUp key } });

Controlling browser's default actions

Browser's default actions to arrow keys, such as scrolling, might need overriding:

document.addEventListener('keydown', function(event) { if(event.key.includes('Arrow')) { event.preventDefault(); // Default scrolling behavior: "Not today!" // Continue with your custom behavior... } });

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:

document.addEventListener('keydown', function(event) { switch(event.key) { case 'ArrowUp': // Up-key functionality case 'ArrowRight': // Right-key functionality // ... And so on } });

This structure is not only scalable but also pleasingly maintainable.