charCodeEvent Property
Example
Get the Unicode value of the pressed keyboard key:
xThe output result is:
Try it Yourself »
More examples are included at the bottom of this article.
Definition and Usage
The charCode property returnsonkeypressthe character code of the key value that triggered the event.
A Unicode character code is a number for a letter (for example, the number "97" represents the letter "a").
Tip:A list of all Unicode characters can be found in ourComplete Unicode Reference Manual。
Tip:If you need to convert a Unicode value to a character, you can use thefromCharCode()method.
Note:If this property is used for theonkeydownoronkeyupevent, the return value is always "0".
Note:This property is read-only.
Note:The which and keyCode properties provide a way to solve browser compatibility. The latest version of DOM events recommends using thekeyproperty to replace this method.
Note:IE8 and earlier versions do not support the which property. Unsupported browsers can use thekeyCodeproperty. However, the keyCode property is invalid in the onkeypress event in Firefox. To be compatible with these browsers, you can use the following code:
Tip:You can also use the keyCode property to detect special keys (such as "caps lock" or arrow keys). The keyCode and charCode properties provide a way to solve browser compatibility. The latest version of DOM events recommends using thekeyproperty to replace this method.
Tip:If you want to check whether the "ALT", "CTRL", "META", or "SHIFT" key is pressed, you can use thealtKey, ctrlKey, metaKeyorshiftKeyproperty.
Browser Support
The numbers in the table indicate the first browser version that supports the property.
| Property | |||||
|---|---|---|---|---|---|
| charCode | Yes | 9.0 | Yes | Yes | Yes |
Syntax
Technical Details
| Return Value: | A number representing the Unicode character code |
|---|---|
| DOM Version: | DOM Level 2 Events |
More Examples
Example
Browser-compatible solution for getting the Unicode value of a key:
var x = event.charCode || event.keyCode;
Try it Yourself »
Example
When the user presses the "O" key, a prompt message is displayed:
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
Convert Unicode value to character:
var y = String.fromCharCode(x); // Convert the value to a character
Try it Yourself »
Related Pages
HTML DOM Reference:key Event Property
HTML DOM Reference:keyCode Event Property
HTML DOM Reference:which Event Property
Other Extensions
Event Object