which
Event Property
Example
Get the Unicode value of the key pressed:
var x = event.which;
x outputs:
119 // 119 is the character "w"
More examples are included at the bottom of this page.
Definition and Usage
The which
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 (the "W" key code is "87"), but they have different character codes, and their outputs are different (the "w" and "W" character codes are "119" and "87") - see the example below for better understanding.
Tip: Use the onkeypress
event if you need to know if the user pressed a printable key (like "a" or "5"). Use the onkeydown
or onkeyup
event if you need to know if the user pressed a function key (like "F1", "CAPS LOCK" or "Home").
Note: The which
property is not supported in IE8 and earlier. For unsupported browsers, you can use the keyCode
property. However, the keyCode
property is not valid in the onkeypress
event in Firefox. To be compatible with these browsers, you can use the following code:
Tip: For a complete list of all Unicode characters, see our Complete 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
The numbers in the table specify the first browser version that fully supports the property.
Property | |||||
---|---|---|---|---|---|
which | Yes | 9.0 | Yes | Yes | Yes |
Syntax
Technical Details
Return Value: | A 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 pressing the "a" key on the keyboard (without using caps lock), the output will be:
Unicode character code: 97
Unicode 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: charCode Event Property