Listening to Keystrokes

Two main events fire when a user interacts with the keyboard:

  • keydown: fires when a key is pressed (and repeats if held down).
  • keyup: fires when a key is released.

The Two Most Important Properties

event.code — The Physical Key

This identifies the physical key on the keyboard, regardless of the current language or layout.

  • 'KeyA', 'KeyZ', 'ShiftLeft', 'Enter', 'ArrowUp'
  • Useful for game controls and keyboard shortcuts.

event.key — The Printed Character

This is the character that will actually be typed, depending on the current keyboard layout and language.

  • 'a' or 'A' (shift changes it), 'ф' (Cyrillic layout), 'Enter'
  • Useful for detecting what the user is typing.

Detecting Key Combinations

document.addEventListener('keydown', function(event) {
  // Detect Ctrl+Z (or Cmd+Z on Mac) for Undo
  if (event.code === 'KeyZ' && (event.ctrlKey || event.metaKey)) {
    alert('Undo action!');
    event.preventDefault(); // Prevent the browser's own undo
  }
});
Caution

The keypress event is deprecated and should no longer be used. Always use keydown or keyup instead.