JavaScript KeyboardEvent code Property: Understanding Physical Key Codes

The JavaScript KeyboardEvent code property provides a string representing the physical key on the keyboard that was pressed. Unlike the key property (which represents the logical key value) or keyCode (which provides a numerical code that can vary based on the operating system and browser), code always gives the same string for a specific physical key, regardless of the keyboard layout, operating system or browser. This makes it especially useful for handling game controls and other applications where consistent physical key bindings are required. This guide will explain how to use the code property effectively, along with examples and use cases.

What is the code Property?

The code property is a read-only string value that identifies the physical key that was pressed during a keyboard event. This property remains consistent across different keyboard layouts, operating systems, and browser configurations, unlike the key or keyCode properties, which can vary. For instance, the key in the physical location for “A” will always return “KeyA” regardless of the user’s current layout. This is crucial for game development and other applications where a specific physical key press needs to be detected reliably.

Why Use the code Property?

Using code offers several advantages:

  • Consistent Across Layouts: The physical key location is always the same, regardless of the user’s keyboard layout (QWERTY, AZERTY, etc.).
  • Reliable Key Detection: You can map physical key locations to actions without being concerned about variations.
  • Ideal for Game Controls: It allows players to use the same physical keys for the same game controls on different machines, regardless of their language and keyboard layout configurations.

Syntax

The code property is accessed directly from a KeyboardEvent object:

element.addEventListener('keydown', function(event) {
    const physicalKeyCode = event.code;
    // Use physicalKeyCode here
});

Key Points

  • The code property returns a string such as “KeyA”, “Space”, “ArrowLeft”, “ShiftLeft”, etc.
  • It’s case-sensitive, so KeyA is different from keya.
  • The physical key remains the same, so pressing “A” on a QWERTY and pressing “Q” on an AZERTY both will result in the “KeyA” code, since the physical key is same.
  • It’s not locale aware, it gives code based on physical key location, not the character that is output.

Examples of Using KeyboardEvent.code

Let’s explore some practical examples of how to use the code property.

Basic Key Code Logging

This example demonstrates how to listen for a keydown event and log the code property of the pressed key.

<p>Press any key to see its physical key code.</p>
<div id="keyLogDiv"></div>

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

  document.addEventListener('keydown', function(event) {
    keyLogDiv.textContent = 'Physical Key Code: ' + event.code;
  });
</script>

Press any key to see its physical key code.

Output: Each time you press a key, the div will display its corresponding code, such as Physical Key Code: KeyA or Physical Key Code: Space.

Using Code for Game Controls

Here’s how you might use the code property to control a simple game character on a canvas.

<canvas
  id="gameCanvas"
  width="200"
  height="200"
  style="border: 1px solid black;"
></canvas>

<script>
  const gameCanvas = document.getElementById('gameCanvas');
  const ctx_game = gameCanvas.getContext('2d');

  let x = 50;
  let y = 50;

  function drawCharacter() {
    ctx_game.clearRect(0, 0, gameCanvas.width, gameCanvas.height);
    ctx_game.fillStyle = 'blue';
    ctx_game.fillRect(x, y, 20, 20);
  }

  drawCharacter();

  document.addEventListener('keydown', function(event) {
    switch (event.code) {
      case 'ArrowUp':
        y -= 10;
        break;
      case 'ArrowDown':
        y += 10;
        break;
      case 'ArrowLeft':
        x -= 10;
        break;
      case 'ArrowRight':
        x += 10;
        break;
    }
    drawCharacter();
  });
</script>

Output: A blue square on a canvas that moves up, down, left, or right when you press the arrow keys, regardless of your keyboard layout. The physical key locations are used here.

Dynamic Key Binding Display

This example demonstrates how to display the physical key codes for specific actions, allowing users to see their key bindings.

<p>Use arrow keys for movement.</p>
<div id="keyBindingDisplay">
  Up: <span id="upKey"></span><br />
  Down: <span id="downKey"></span><br />
  Left: <span id="leftKey"></span><br />
  Right: <span id="rightKey"></span>
</div>

<script>
  const upKeyDisplay = document.getElementById('upKey');
  const downKeyDisplay = document.getElementById('downKey');
  const leftKeyDisplay = document.getElementById('leftKey');
  const rightKeyDisplay = document.getElementById('rightKey');

  document.addEventListener('keydown', function(event) {
    switch (event.code) {
      case 'ArrowUp':
        upKeyDisplay.textContent = event.code;
        break;
      case 'ArrowDown':
        downKeyDisplay.textContent = event.code;
        break;
      case 'ArrowLeft':
        leftKeyDisplay.textContent = event.code;
        break;
      case 'ArrowRight':
        rightKeyDisplay.textContent = event.code;
        break;
    }
  });
</script>

Use arrow keys for movement.

Up:
Down:
Left:
Right:

Output: The HTML shows which physical keys are currently assigned for each action, allowing developers to create clear documentation or settings menus.

Browser Support

The KeyboardEvent.code property is widely supported across all modern web browsers.

Browser Support
Chrome Yes
Firefox Yes
Safari Yes
Edge Yes
Opera Yes

Note: This broad support makes it a reliable choice for developing web applications that require consistent handling of keyboard input. 👍

Conclusion

The KeyboardEvent.code property is an invaluable tool for web developers, offering a consistent and reliable way to detect physical key presses. Its ability to remain consistent across different keyboard layouts, operating systems, and browsers makes it crucial for creating robust and user-friendly applications. By using this property, you can create games, interactive tools, and other web applications that work predictably for all users. This guide provides a clear understanding of how to use the code property effectively, enabling you to create more sophisticated and reliable user experiences.