Latest web development tutorials

charCode event properties

Event Object Reference Event objects

Examples

Being pressed keyboard keys Unicode value ::

var x = event.charCode;

x The output is:

119 // 119 is the letter "w"

try it"

Bottom of this article contains more examples.


Definitions and use

charCode property returns onkeypress event triggered keys letter code.

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

Note: A list of all Unicode characters can see our complete Unicode reference manual .

Tip: If you need to convert Unicode character value, you can use fromCharCode () method.

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

Note: This property is read-only.

Note: which keyCode property and provides a solution method for browser compatibility, the latest version of the DOM event recommended key attribute as an alternative method.

Note: IE8 and earlier versions do not support which attributes. Unsupported browser can use keyCode property. However, keyCode properties in the Firefox browser onkeypress event is invalid. Compatible with these browsers you can use the following code:

var x = event.charCode || event.keyCode; // use charCode or keyCode, this may support different browsers

Tip: You can also use the keyCode property to detect special keys (such as "caps lock" or the arrow keys). keyCode and charCode property provides a solution method for browser compatibility, the latest version of the DOM event recommended key attribute as an alternative method.

Tip: If you want to see if the press "ALT", "CTRL", "META" or "SHIFT" key, you can use altKey , ctrlKey , metakey or shiftKey property.


Browser Support

Figures in the table represent the first browser to support the property version number.

Attributes
charCode Yes 9.0 Yes Yes Yes


grammar

event .charCode

technical details

return value: Number that represents the Unicode character code
DOM version: DOM Level 2 Events


Examples

More examples

Examples

Unicode values ​​for the key browser compatible solution:

// If the browser does not support charCode, use the keyCode (IE8 and earlier versions)
var x = event.charCode || event.keyCode;

try it"

Examples

When the user presses the "O" key to bring up the message:

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

try it"

Examples

To convert Unicode values ​​for the characters:

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

try it"


Related Pages

HTML DOM Reference Manual: Key Event Properties

HTML DOM Reference Manual: the keyCode property event

HTML DOM Reference Manual: Which Event Properties


Event Object Reference Event objects