JavaScript KeyboardEvent charCode Property: Understanding Character Codes

The charCode property of the JavaScript KeyboardEvent interface is used to obtain the character code of a key that has been pressed. This property is particularly useful when you need to identify which character was entered, especially in cases involving text input. Unlike the keyCode property, which returns the physical key code, charCode returns the numeric Unicode value of the character associated with the pressed key.

What is the charCode Property?

The charCode property is an integer representing the Unicode value of the character generated by a keyboard event. It’s one of several properties available in KeyboardEvent objects, each designed to capture different aspects of keyboard interactions.

Purpose of the charCode Property

The primary purpose of the charCode property is to:

  • Capture the specific character that was input
  • Identify alphabetic characters, numbers, and special characters
  • Determine the character code for further processing or validation
  • Handle text input and manipulate strings based on character codes

Syntax

The charCode property is accessed directly from a KeyboardEvent object within an event listener.

event.charCode;
  • event: A KeyboardEvent object passed to the event listener function.
  • Return Value: An integer representing the Unicode value of the character or 0 if the key does not generate a character.

Key Points about charCode

  • Character-Specific: charCode is character-specific, returning the Unicode code point of the generated character.
  • Keypress Event: It’s mainly relevant for the keypress event. It is deprecated and not recommended for keydown or keyup events. ⚠️
  • Unicode Values: The returned value is a Unicode value, allowing it to handle a wide range of characters.
  • Non-Character Keys: For keys like Shift, Ctrl, Alt, Function keys, and arrow keys which don’t generate characters, charCode will be 0.
  • Deprecated: While charCode provides useful character information, it’s deprecated for keydown and keyup events. Use the key or code properties where possible.

Examples

Let’s explore several practical examples to illustrate how to use the charCode property effectively.

Basic Example: Displaying Character Codes

This example shows how to listen for the keypress event and display the character code of the pressed key:

<!DOCTYPE html>
<html>
<head>
    <title>KeyboardEvent charCode Example</title>
</head>
<body>
  <p>Press any key to see its charCode:</p>
  <div id="charInfo"></div>

  <script>
    const charInfoDiv = document.getElementById('charInfo');
    document.addEventListener('keypress', function(event) {
        const charCode = event.charCode;
        charInfoDiv.textContent = 'charCode: ' + charCode;
    });

</script>
</body>
</html>

Output:

When a key is pressed, for example, ‘A’, the output will display charCode: 65 because the char code for the capital letter ‘A’ is 65.

Explanation:

  • We attach a keypress event listener to the document.
  • When a key is pressed, the event handler receives a KeyboardEvent object.
  • The charCode property is accessed, and its value is displayed in the #charInfo div.

Example: Character Validation

This example demonstrates how to use charCode to validate if the input is a digit:

<!DOCTYPE html>
<html>
<head>
    <title>Character Validation Example</title>
</head>
<body>
    <input type="text" id="numberInput" placeholder="Enter a number">
    <p id="validationMessage"></p>

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

       numberInput.addEventListener('keypress', function(event) {
          const charCodeValidate = event.charCode;
          if (charCodeValidate < 48 || charCodeValidate > 57) {
               event.preventDefault(); // Prevent non-numeric input
               validationMessage.textContent = 'Please enter only numbers';
          } else {
               validationMessage.textContent = ''; // Clear message on valid input
          }
       });

</script>
</body>
</html>

Output:

When a key that is not a digit (0-9) is pressed, the input will not be added to the text field and a validation message saying Please enter only numbers will be shown. If a digit is pressed, it will be accepted.

Explanation:

  • We add a keypress listener to the <input> element.
  • Inside the handler, we access the charCode.
  • We check if the code is within the numeric range (48-57 for 0-9).
  • If not, event.preventDefault() is called to stop the character from being entered and an error message is shown.
  • If it is within numeric range, validation message is set to empty.

Example: Character Conversion

This example shows how to convert charCode to a character and append it to a string.

<!DOCTYPE html>
<html>
<head>
    <title>Character Conversion Example</title>
</head>
<body>
    <p>Press keys to see the characters:</p>
    <div id="charDisplay"></div>

    <script>
        const charDisplayDiv = document.getElementById('charDisplay');
        let inputString = '';

        document.addEventListener('keypress', function(event) {
           const charCodeConvert = event.charCode;
           const charValue = String.fromCharCode(charCodeConvert);
           inputString += charValue;
           charDisplayDiv.textContent = 'Input: ' + inputString;
        });

</script>
</body>
</html>

Output:

As keys are pressed, the typed character will be displayed. For example if ‘Hello’ is typed, the output will display Input: Hello.

Explanation:

  • We set up a keypress event listener on the document.
  • We obtain the charCode.
  • String.fromCharCode() is used to convert the charCode to its corresponding character.
  • The character is added to a string, which is displayed in the charDisplay div.

Example: Handling Special Characters

This example shows how to detect specific characters like the space bar or enter key based on their character codes:

<!DOCTYPE html>
<html>
<head>
  <title>Special Character Detection</title>
</head>
<body>
  <p>Press Spacebar or Enter:</p>
  <div id="specialCharInfo"></div>

  <script>
    const specialCharInfoDiv = document.getElementById('specialCharInfo');
    document.addEventListener('keypress', function(event) {
        const specialCharCode = event.charCode;
        if (specialCharCode === 32) {
            specialCharInfoDiv.textContent = 'Spacebar Pressed';
        } else if (specialCharCode === 13) {
            specialCharInfoDiv.textContent = 'Enter Key Pressed';
        }
    });

</script>
</body>
</html>

Output:

When the Spacebar is pressed, the output will display Spacebar Pressed. When the Enter Key is pressed, the output will display Enter Key Pressed.

Explanation:

  • We attach a keypress event listener.
  • Inside the handler, we obtain the charCode.
  • We check if the charCode is 32 (Spacebar) or 13 (Enter).
  • Based on the detected code, we display the corresponding message.

Browser Support

The charCode property is widely supported across all modern browsers. However, it’s essential to keep in mind that charCode is deprecated for keydown and keyup events.

Browser Support
Chrome Fully Supported
Firefox Fully Supported
Safari Fully Supported
Edge Fully Supported
Opera Fully Supported

Note: While the charCode property is supported by all major browsers, it is still recommended to use the key or code properties when available, especially when working with keydown and keyup events, since charCode is deprecated for these events. 🧐

Conclusion

The charCode property of the KeyboardEvent interface provides valuable information about the character produced when a key is pressed. It enables developers to handle text input, perform validation, and manipulate strings. By understanding how to use charCode, you can improve the interactivity and responsiveness of your web applications. Although charCode is deprecated for the keydown and keyup events, it’s still relevant in the context of the keypress event. Using this property correctly allows you to handle character inputs efficiently and accurately, making your web applications more user-friendly.