Use the keydown event and event.key to detect arrow-key presses. This replaces older code that compared numeric keyCode values such as 37, 38, 39 and 40.
Click the demo box, then press an arrow key.
No arrow key detected yet.
const messages = {
ArrowLeft: 'Left arrow pressed',
ArrowUp: 'Up arrow pressed',
ArrowRight: 'Right arrow pressed',
ArrowDown: 'Down arrow pressed'
};
element.addEventListener('keydown', (event) => {
if (messages[event.key]) {
event.preventDefault();
console.log(messages[event.key]);
}
});
event.key reports ArrowLeft, ArrowRight, ArrowUp and ArrowDown. Comparing these names is easier to read than remembering numeric key codes.
Keyboard events go to the currently focused element. The demo box uses tabindex="0" so keyboard users can focus it naturally. For a site-wide shortcut you can listen on document, but local listeners are safer when only one component needs the keys.
Arrow keys normally scroll pages or move within controls. Call event.preventDefault() only inside a component where your own arrow-key behavior intentionally replaces that normal action.
// Legacy
if (event.keyCode === 37) { /* left */ }
// Modern
if (event.key === 'ArrowLeft') { /* left */ }
← Event Handling Move an image with arrow keys →
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.