Event keyCode property
Examples
Being Unicode values by pressing the keys on the keyboard:
x The output is:
try it"
Bottom of this article contains more examples.
Definitions and use
keyCode property returns onkeypress event trigger key character code value or onkeydown or onkeyup event key code.
Is the difference between the two types of code:
- Character code - Indicates an ASCII character
- Keyboard codes - represents the number keys on the keyboard real
Tip: If you need to know the user presses the print key (such as "a" or "5"), it is recommended to use onkeypress event. If you need to know the user presses a function key (such as "F1", "CAPS LOCK" or "Home") can be used onkeydown or onkeyup event.
Note: In Firefox ,, keyCode property onkeypress event is invalid (return 0). Browser compatibility issues, can be used with which and keyCode properties to solve:
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: 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.
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
Attributes | |||||
---|---|---|---|---|---|
keyCode | Yes | Yes | Yes | Yes | Yes |
grammar
technical details
return value: | Number that represents the Unicode character code or Unicode key code |
---|---|
DOM version: | DOM Level 2 Events |
More examples
Examples
Use onkeypress and onkeydown to demonstrate the difference between character code and keyboard codes:
function uniCharCode (event) {
var char = event.which || event.keyCode;
document.getElementById ( "demo") .innerHTML = "Unicode CHARACTER code:" + char;
}
function uniKeyCode (event) {
var key = event.keyCode;
document.getElementById ( "demo2") .innerHTML = "Unicode KEY code:" + key;
}
When pressed on the keyboard "a" key (do not use Caps Lock), the output results are as follows:
Unicode key code: 65
try it"
Examples
If you press the Esc key to pop up a message:
function myFunction (event) {
var x = event.keyCode;
if (x == 27) {// 27 ESC key is
alert ( "You pressed the Escape key !");
}
}
try it"
Examples
To convert Unicode values for the characters (not available for the function keys):
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