JavaScript KeyboardEvent which Property: Identifying Key Codes

The which property of the JavaScript KeyboardEvent interface is used to retrieve the numeric Unicode key code of the key that was pressed or released. While modern browsers and web standards prefer using the key and code properties for more reliable and descriptive key information, the which property remains a part of the event object for legacy support and is still helpful for certain use cases. This article explores the which property, its significance, and practical applications, with clear examples to help you understand and use it effectively.

Purpose of the which Property

The primary purpose of the which property is to provide a numeric identifier for the key that triggered a keyboard event. This numeric identifier is based on the Unicode value of the key, which was a common method for identifying keys before the introduction of the more descriptive key and code properties.
While newer properties offer more detailed information, the which property can still be helpful when working with older code or needing numerical key code representations.

Syntax

The which property is accessed directly from a KeyboardEvent object within an event handler:

element.addEventListener('keydown', function(event) {
  const keyCode = event.which;
  // ... use the keyCode
});

Here, the event.which returns a number representing the numeric key code.

Understanding the Key Codes

The key codes returned by the which property correspond to Unicode values. Common key codes include:

  • 13: Enter key
  • 27: Escape key
  • 32: Spacebar
  • 37: Left arrow key
  • 38: Up arrow key
  • 39: Right arrow key
  • 40: Down arrow key
  • 4857: Numbers 0 to 9
  • 6590: Alphabets A to Z
  • … and more

It is important to remember that key codes for letters return the uppercase ASCII codes regardless of whether the shift key is used.

Example: Displaying Key Codes on Key Press

Here is an example of how to use the which property to display the key codes of pressed keys in a webpage.

<div style="padding: 20px;">
    <label for="keyInput">Press any key:</label>
    <input type="text" id="keyInput" placeholder="Press a key here" />
    <div id="keyCodeDisplay" style="margin-top: 10px;">Key Code: <span id="codeValue"></span></div>
</div>

<script>
  const keyInputWhich = document.getElementById("keyInput");
  const keyCodeDisplayWhich = document.getElementById("keyCodeDisplay");
  const codeValueWhich = document.getElementById("codeValue");

  keyInputWhich.addEventListener("keydown", function (event) {
    const keyCodeWhich = event.which;
      codeValueWhich.textContent = keyCodeWhich;
    });
</script>

In this example, an input field is used to capture the keyboard events. When a key is pressed, the event listener retrieves the key code using the which property and displays it in the designated span.


Key Code:

Example: Using key codes for specific actions

This example demonstrates how to use the which property to trigger different actions based on specific key codes. A canvas is used to visualize a circle, and arrow keys are used to move the circle’s position.

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

<script>
  const canvasMove = document.getElementById("canvasMoveCircle");
  const ctxMove = canvasMove.getContext("2d");

  let xMove = 50;
  let yMove = 50;

    function drawCircle() {
    ctxMove.clearRect(0, 0, canvasMove.width, canvasMove.height);
      ctxMove.beginPath();
    ctxMove.arc(xMove, yMove, 20, 0, 2 * Math.PI);
    ctxMove.fillStyle = "blue";
      ctxMove.fill();
    }

    drawCircle();

  document.addEventListener("keydown", function (event) {
    const keyCodeMove = event.which;
    switch (keyCodeMove) {
        case 37: // Left arrow
            xMove -= 10;
            break;
        case 38: // Up arrow
            yMove -= 10;
            break;
      case 39: // Right arrow
            xMove += 10;
            break;
      case 40: // Down arrow
            yMove += 10;
            break;
    }
       drawCircle();
  });
</script>

In this example, the switch statement checks the key code and updates the position of the circle accordingly. The circle moves based on which arrow key is pressed.

Key Differences: which, key and code

While which provides numeric key codes, the key and code properties of KeyboardEvent offer more informative details:

  • key property: Returns a string representing the key pressed, such as "Enter", "Space", "a", "A".
  • code property: Returns a string representing the physical key on the keyboard, such as "Enter", "Space", "KeyA".

These properties are generally more reliable and easier to use in modern web development.

When to Use which

While key and code are preferred in most cases, there are scenarios where which might still be useful:

  • Legacy Code: When working with older JavaScript code that relies on numeric key codes.
  • Specific Numeric Logic: When a specific numerical representation of key presses is required for logical comparisons.
  • Compatibility: To maintain consistency when integrating old code with new functionalities, especially if converting that code is a big hassle.

Browser Compatibility

The which property enjoys broad support across all major browsers, including older versions. However, it is important to be aware that the which property is deprecated in favor of key and code, but is still supported for legacy code reasons.
For new projects, it is recommended to use the key or code properties for more robust key identification.

Tips and Best Practices

  • Use key or code when possible: For new projects, prefer key and code over which for better readability and maintainability.
  • Test Across Browsers: When relying on key codes, thoroughly test in different browsers to ensure cross-browser consistency, as differences might arise.
  • Avoid Hardcoding Numbers: Use descriptive constants for key codes instead of raw numbers for better understanding in code, where possible.
  • Legacy Code: Be aware of the limitations and differences between which and the modern key and code properties, if working with old code.

Conclusion

The which property of the JavaScript KeyboardEvent is an old but still supported mechanism for retrieving the numeric key code of a pressed key. While it’s essential to understand its functionality, modern web development should prefer the more descriptive key and code properties for identifying key presses. However, which remains valuable for legacy support and certain specific use cases. This comprehensive guide, along with the examples provided, should help you understand and use the which property effectively in your JavaScript projects.