正在加载,请稍候…

Understanding JavaScript Keycodes: A Developer's Guide

Learn how keyboard events work in JavaScript, how to use the Keycode Info tool to identify key events, and common pitfalls to avoid.

Understanding JavaScript Keycodes: A Developer's Guide

Keyboard events are fundamental to interactive web applications. Whether you're building a game, a shortcut-driven editor, or an accessible form, understanding how to capture and interpret key presses is essential. This guide dives into the JavaScript keyboard event model, explains the properties available on the event object, and shows you how to use our Keycode Info tool to quickly identify key codes.

The Keyboard Event Lifecycle

When a user presses a key, three events fire in sequence:

  1. keydown – Fires when a key is first pressed. It repeats while the key is held down (before the operating system's repeat delay kicks in).
  2. keypress – Fires for keys that produce a character value (letters, numbers, symbols). This event is deprecated but still widely supported. It does not fire for modifier keys like Shift or Ctrl.
  3. keyup – Fires when the key is released.

For most modern applications, keydown and keyup are sufficient. keypress should be avoided due to its inconsistent behavior across browsers and its deprecation.

Key Properties on the Event Object

The KeyboardEvent object provides several properties to identify which key was pressed and its state:

Property Description Example (pressing 'a')
key The key value as a string. For printable characters, it's the character itself. For special keys, it's a named string like "Enter", "ArrowUp", or "Shift". "a" or "A" (with Shift)
code The physical key location on the keyboard, independent of the current keyboard layout. Values like "KeyA", "Digit1", "ArrowUp". "KeyA"
keyCode A numeric code representing the key. Deprecated but still used in legacy code. For 'a' it's 65, for 'A' it's also 65 (case insensitive). 65
charCode The Unicode value of the character. Only available in keypress. Deprecated. 97 (for 'a'), 65 (for 'A')
shiftKey Boolean indicating if Shift was held. false
ctrlKey Boolean indicating if Ctrl was held. false
altKey Boolean indicating if Alt was held. false
metaKey Boolean indicating if Meta (Cmd on Mac, Windows key) was held. false

Why key and code Matter More Than keyCode

The legacy keyCode property is deprecated and behaves inconsistently across browsers and keyboard layouts. For example, pressing the ';' key on a US keyboard gives keyCode 186, but on a French AZERTY layout the same physical key might produce a different character and code. In contrast:

  • key gives you the logical character (e.g., "a" vs "A" depending on Shift state). Use it when you care about the character typed.
  • code gives you the physical key location (e.g., "KeyA" regardless of layout or Shift). Use it for game controls or shortcuts that depend on key position.

Worked Example: Building a Keyboard Shortcut Logger

Let's build a simple HTML page that logs every key event and displays the relevant properties. You can then compare the output with our Keycode Info tool to verify your understanding.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Key Logger</title>
  <style>
    #log { white-space: pre-wrap; font-family: monospace; }
  </style>
</head>
<body>
  <h1>Press any key</h1>
  <div id="log"></div>

  <script>
    const logDiv = document.getElementById('log');

    document.addEventListener('keydown', (event) => {
      const line = [
        `Event: ${event.type}`,
        `key: "${event.key}"`,
        `code: "${event.code}"`,
        `keyCode: ${event.keyCode}`,
        `shiftKey: ${event.shiftKey}`,
        `ctrlKey: ${event.ctrlKey}`,
        `altKey: ${event.altKey}`,
        `metaKey: ${event.metaKey}`
      ].join(' | ');
      
      logDiv.textContent += line + '\n';
      
      // Prevent default for certain keys if needed
      // event.preventDefault();
    });
  </script>
</body>
</html>

Open this page in your browser and press various keys. Notice that:

  • Pressing 'a' gives key: "a", code: "KeyA", keyCode: 65.
  • Pressing Shift+a gives key: "A", code: "KeyA" (same code, different key).
  • Pressing the left arrow gives key: "ArrowLeft", code: "ArrowLeft", keyCode: 37.

Keyboard event logging example

Using the Keycode Info Tool

Our Keycode Info tool provides an interactive way to see all properties of a key event in real time. You can press any key and instantly see the key, code, keyCode, and modifier states. This is especially useful when you're implementing keyboard shortcuts and need to confirm the exact values for a specific key combination.

For example, if you want to bind Ctrl+S for saving, you can press Ctrl+S in the tool and see that ctrlKey is true, key is "s" (or "S" if CapsLock is on), and code is "KeyS". This confirms that your event handler should check for event.ctrlKey && event.key === 's' (case-insensitive).

Common Pitfalls

  • Using keyCode in new code. It's deprecated and may break in future browsers. Use key or code instead.
  • Forgetting that key is case-sensitive. When checking for a letter, always compare with the lowercase version (e.g., event.key.toLowerCase() === 's') to handle CapsLock or Shift.
  • Assuming keypress fires for all keys. It only fires for printable characters. Use keydown for non-printable keys like arrows, Enter, or Escape.
  • Not preventing default behavior. If you're overriding a browser shortcut (like Ctrl+S), call event.preventDefault() to stop the browser from saving the page.
  • Ignoring keyboard layout differences. If your app relies on specific physical key positions (e.g., WASD for games), use code instead of key.

Security and Performance Considerations

  • Never trust client-side input for security. Keyboard events can be spoofed or blocked by browser extensions. Always validate input server-side.
  • Avoid heavy processing in event handlers. Keyboard events fire rapidly, especially when a key is held down. Debounce or throttle if you need to perform expensive operations.
  • Be mindful of accessibility. Don't rely solely on keyboard shortcuts; provide alternative UI elements for users who cannot use a keyboard.

FAQ

What is the difference between key and code?

key represents the character or function of the key (e.g., "a", "Enter", "Shift"), while code represents the physical key location (e.g., "KeyA", "Enter", "ShiftLeft"). key changes with modifier keys and keyboard layout; code does not.

Why is keyCode deprecated?

keyCode was never standardized properly and behaves inconsistently across browsers and keyboard layouts. The Web Hypertext Application Technology Working Group (WHATWG) recommends using key or code instead.

How do I detect a key combination like Ctrl+Shift+F?

Check the modifier properties (ctrlKey, shiftKey, altKey, metaKey) along with the key or code property. For example:

document.addEventListener('keydown', (e) => {
  if (e.ctrlKey && e.shiftKey && e.key === 'F') {
    // handle Ctrl+Shift+F
  }
});

Does keydown repeat when a key is held?

Yes. The keydown event fires repeatedly according to the operating system's repeat rate. You can check event.repeat (a boolean) to distinguish initial press from repeats.

Can I use the Keycode Info tool offline?

The tool is web-based and requires an internet connection. However, you can save the page or use the code snippet above to create your own local version.


Understanding keyboard events is a cornerstone of interactive web development. By using modern properties like key and code, and leveraging tools like our Keycode Info, you can build robust, cross-browser keyboard interactions.