charCode
Event Property
Example
Get the Unicode value of the key pressed:
var x = event.charCode;
x outputs:
119 // 119 is the letter "w"
More examples are available at the bottom of this page.
Definition and Usage
The charCode
property returns the Unicode character code of the key that triggered the onkeypress
event.
The Unicode character code is a numeric value for a character (e.g., "97" represents the letter "a").
Tip: For a full list of all Unicode characters, see our Complete Unicode Reference.
Tip: To convert a Unicode value to a character, use the fromCharCode() method.
Note: If this property is used with onkeydown
or onkeyup
events, the return value is always "0".
Note: This property is read-only.
Note: The which
and keyCode
properties provide a way to deal with browser compatibility. The latest DOM events recommend using the key property instead.
Note: IE8 and earlier do not support the which
property. Unsupported browsers can use the keyCode property. However, the keyCode
property is not valid in Firefox during the onkeypress
event. For compatibility, you can use the following code:
Tip: You can also use the keyCode
property to detect special keys (like "caps lock" or arrow keys). The keyCode
and charCode
properties provide a way to deal with browser compatibility. The latest DOM events recommend using the key property instead.
Tip: To check if "ALT", "CTRL", "META", or "SHIFT" keys are pressed, use the altKey, ctrlKey, metaKey, or shiftKey properties.
Browser Support
The numbers in the table specify 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
A cross-browser solution to get the Unicode value of the key pressed:
// If charCode is not supported, use keyCode (IE8 and earlier)
var x = event.charCode || event.keyCode;
Example
Show an alert message when the "O" key is pressed:
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!");
}
}
Example
Convert a Unicode value to a character:
var x = event.charCode || evt.keyCode; // Get Unicode value
var y = String.fromCharCode(x); // Convert value to character
Related Pages
HTML DOM Reference: key Event Property
HTML DOM Reference: keyCode Event Property
HTML DOM Reference: which Event Property