Detect Arrow-Key Presses in JavaScript

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.

Arrow-key demo area

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]);
  }
});
Table of Contents

Arrow-Key Names Top ↑

event.key reports ArrowLeft, ArrowRight, ArrowUp and ArrowDown. Comparing these names is easier to read than remembering numeric key codes.

Keyboard Events Need a Focus Target Top ↑

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.

When to Prevent Arrow-Key Defaults Top ↑

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.

Replacing keyCode 37-40 Top ↑

// Legacy
if (event.keyCode === 37) { /* left */ }

// Modern
if (event.key === 'ArrowLeft') { /* left */ }

← Event Handling Move an image with arrow keys →




Subscribe to our YouTube Channel here



plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer