SyntaxStudy
Sign Up
JavaScript Beginner 7 min read

Keyboard Events

Keyboard Events

Keyboard events allow you to respond to user key presses, enabling keyboard shortcuts, game controls, and enhanced form accessibility. Three event types cover the full lifecycle of a key interaction.

keydown, keypress (deprecated), keyup

keydown fires when a key is pressed down — it fires repeatedly if the key is held. keyup fires when the key is released. keypress is deprecated and should not be used in new code.

Key Properties

The event object provides two important properties. event.key returns the logical key value (e.g., "a", "Enter", "ArrowUp") and is the property to use in modern code. event.code returns the physical key code (e.g., "KeyA"), independent of keyboard layout — useful for gaming controls.

Modifier Keys

event.shiftKey, event.ctrlKey, event.altKey, and event.metaKey are boolean properties indicating whether modifier keys were held during the event.

Example
document.addEventListener('keydown', function(e) {
  console.log('key:', e.key, 'code:', e.code);
  if (e.key === 'Enter') {
    console.log('Enter pressed');
  }
  if (e.ctrlKey && e.key === 's') {
    e.preventDefault();
    console.log('Ctrl+S intercepted');
  }
});
document.addEventListener('keyup', function(e) {
  console.log(e.key, 'released');
});
const input = document.querySelector('input');
input.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') this.blur();
});
Pro Tip

Use event.key for logical input handling (what the user typed) and event.code for physical key position (game controls, shortcuts that should work regardless of keyboard layout).