KeyboardEvent charCode Property

Definition and Usage

The charCode property returns the Unicode character code of the key that triggered onkeypress Event of the key's Unicode character code.

Unicode character code is a number assigned to a character (for example, the number "97" represents the letter "a").

Tip:For a list of all Unicode characters, please refer to our Complete Unicode Reference.

Tip:If you want to convert a Unicode value to a character, please use fromCharCode() method.

Note:If this property is used for onkeydown or onkeyup If this property is used for an event, the return value is always "0".

Note:This property is read-only.

Note:IE8 and earlier versions do not support the charCode property. However, for these browser versions, you can use keyCode propertyOr, for cross-browser solutions, you can use the following code:

var x = event.charCode || event.keyCode; // Use charCode or keyCode depending on browser support

Tip:You can also use the keyCode property to detect special keys (such as the Caps Lock or arrow keys). However, both keyCode and charCode properties are provided for compatibility reasons. The latest DOM event specification recommends using the key property (if available).

Tip:If you want to know whether the "ALT", "CTRL", "META", or "SHIFT" key was pressed when the keydown event occurred, use altKey,ctrlKey/,metaKey or shiftKey Properties.

Example

Example 1

Get the Unicode value of the pressed keyboard key:

var x = event.charCode;

Try It Yourself

Example 2

Cross-browser solution to get the Unicode value of the pressed keyboard key:

// If the browser supports it, use charCode; otherwise, use keyCode (for IE8 and earlier versions)
var x = event.charCode || event.keyCode;

Try It Yourself

Example 3

If the user presses the "O" key, prompt some text:

function myFunction(event) {
  var x = event.charCode || event.keyCode;
  if (x == 111 || x == 79) { // o is 111, O is 79
    alert("You pressed the 'O' key!");
  }
}

Try It Yourself

Example 4

Convert the Unicode value to a character:

var x = event.charCode || evt.keyCode;   // Get the Unicode value
var y = String.fromCharCode(x);          // Convert the value to a character

Try It Yourself

Syntax

event.charCode

Technical Details

Return Value: Numeric value representing the Unicode character code.
DOM Version: DOM Level 2 Events

Browser Support

The numbers in the table indicate the first browser version that fully supports the property.

Properties Chrome IE Firefox Safari Opera
charCode Support 9.0 Support Support Support

Related Pages

HTML DOM Reference Manual:KeyboardEvent key Property

HTML DOM Reference Manual:KeyboardEvent keyCode Property

HTML DOM Reference Manual:KeyboardEvent which Property