keyCode
Event Property
Example
Get the Unicode value of the key pressed:
x Output result:
119 // 119 is the character
"w"
More examples are included at the bottom of this page.
Definition and Usage
The keyCode property returns the character code of the key that triggered the onkeypress event, or the key code of the key that triggered the onkeydown or onkeyup event.
The difference between the two code types is:
Character code - A number representing an ASCII character
Key code - A number representing a physical key on the keyboard
The values of these two types are not always equal. For example, the lowercase character "w" and the uppercase character "W" have the same key code because they are on the same key ("W" key code is "87"), but they have different character codes, and their outputs are different ("w" and "W" character codes are "119" and "87") - see the example below for better understanding.
Tip: If you need to know if the user has pressed a printable key (like "a" or "5"), it is recommended to use the onkeypress event. If you need to know if the user has pressed a function key (like "F1", "CAPS LOCK" or "Home"), you can use the onkeydown or onkeyup event.
Note: In Firefox, the keyCode property is not valid (returns 0) in the onkeypress event. Due to browser compatibility issues, you can use both the which and keyCode properties together to solve this:
Tip: For a complete list of Unicode characters, see our Full Unicode Reference.
Tip: If you need to convert a Unicode value to a character, you can use the fromCharCode() method.
Note: This property is read-only.
Note: The which and keyCode properties provide a way to solve browser compatibility issues. The latest version of the DOM Events recommends using the key property instead.
Tip: If you want to check if the "ALT", "CTRL", "META" or "SHIFT" keys were pressed, you can use the altKey, ctrlKey, metaKey or shiftKey properties.
Browser Support
Property | |||||
---|---|---|---|---|---|
keyCode | Yes | Yes | Yes | Yes | Yes |
Syntax
Technical Details
Return Value: | Number, representing the Unicode character code or Unicode key code |
---|---|
DOM Version: | DOM Level 2 Events |
--- | --- |
More Examples
Example
Demonstrate the difference between character code and key code using onkeypress and onkeydown:
When the "a" key is pressed on the keyboard (without using caps lock), the output is as follows:
Unicode character code: 97Unicode key code: 65
Example
Show an alert message if the Esc key is pressed:
Example
Convert a Unicode value to a character (does not work for function keys):
Related Pages
HTML DOM Reference: key Event Property
HTML DOM Reference: keyCode Event Property
HTML DOM Reference: which Event Property