KeyboardEvent key property
Definition and Usage
The key property returns the identifier of the key pressed at the time of the key event.
The key identifier is a string that identifies the keyboard button. The return value of this property can be one of the following strings:
- Single character (such as "a", "W", "4", "+", or "$")
- Multi-character (such as "F1", "Enter", "HOME", or "CAPS LOCK")
Note:This property is read-only.
Tip:If you want to know whether the "ALT", "CTRL", "META", or "SHIFT" key was pressed at the time of the key event, use altKey,ctrlKey,metaKey or shiftKey Property.
Example
Example 1
Get the pressed keyboard button at the time of the key event:
var x = event.key;
Example 2
If the user presses the "A" key, prompt some text:
var x = event.key; // If the pressed keyboard button is "a" or "A" (using CapsLock or Shift), prompt some text. if (x == "a" || x == "A") { alert("You pressed the 'A' key!"); }
Syntax
event.key
Technical Details
Return Value: |
A string representing the pressed keyboard button. Possible Values:
Note:Returns undefined in Safari. |
---|---|
DOM Version: | DOM Level 3 |
Browser Support
The numbers in the table indicate the first browser version that fully supports this property.
Property | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
key | 51.0 | 9.0 | 23.0 | Not supported | 38.0 |
Related Pages
HTML DOM Reference Manual:KeyboardEvent keyCode Property
HTML DOM Reference Manual:KeyboardEvent which Property
HTML DOM Reference Manual:KeyboardEvent charCode Property