THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

KeyboardEvent charCode Property

Event Object Reference Event Object

Example

Get the Unicode value of the pressed keyboard key:

var x = event.charCode;

The result of x could be:

119   // 119 is the character "w"
Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The charCode property returns the Unicode character code of the key that triggered the onkeypress event.

The Unicode character code is the number of a character (e.g. the number "97" represents the letter "a").

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

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

Note: If this property is used on onkeydown or onkeyup events, the returned value is always "0".

Note: This property is read-only.

Note: The charCode property is not supported in IE8 and earlier. However, for these browser versions, you can use the keyCode property. Or, for a cross-browser solution, you could use the following code:

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

Tip: You can also use the keyCode property to detect special keys (e.g. "caps lock" or arrow keys). However, both the keyCode and charCode property is provided for compatibility only. The latest version of the DOM Events Specification recommend using the key property instead (if available).

Tip: If you want to find out whether the "ALT", "CTRL", "META" or "SHIFT" key was pressed when a key event occured, use the altKey, ctrlKey, metaKey or shiftKey property.


Browser Support

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

Property
charCode Yes 9.0 Yes Yes Yes

Syntax

event.charCode

Technical Details

Return Value: A Number, representing the Unicode character code
DOM Version: DOM Level 2 Events

Examples

More Examples

Example

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

// Use charCode if the browser supports it, otherwise use keyCode (for IE8 and earlier)
var x = event.charCode || event.keyCode;
Try it Yourself »

Example

Alert some text if the user presses the "O" key:

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

Convert the Unicode value into a character:

var x = event.charCode || evt.keyCode;   // Get the Unicode value
var y = String.fromCharCode(x);          // Convert the value into a character
Try it Yourself »

Related Pages

HTML DOM reference: KeyboardEvent key Property

HTML DOM reference: KeyboardEvent keyCode Property

HTML DOM reference: KeyboardEvent which Property


Event Object Reference Event Object