key event attribute
Example
Get the keyboard button when a key is pressed:
var
x = event.key;
x The output is:
Enter
Try it »
The bottom of this article contains more examples.
Definition and usage
The key event returns the identifier of the key when it is pressed.
The key identifier is a string representing a keyboard button; the return value of this property can be:
- A single letter (such as "a", "W", "4", "+" or "$")
- Multiple letters (such as "F1", "Enter", "HOME" or "CAPS LOCK")
Tip: If you want to check whether the "ALT", "CTRL", "META" or "SHIFT" keys are pressed, you can use the property. altKey, ctrlKey, metaKey or shiftKey attribute.
Browser support
The numbers in the table indicate the version number of the first browser that supports this property.
| property | |||||
|---|---|---|---|---|---|
| key | Not supported | 9.0 | 23.0 | Not supported | Not supported |
Syntax
event
.key
Technical Details
| Return value: | A string representing the key button.
可能值:
More examples
Example
Pop up a prompt message when the user presses the "A" key:
var
x = event.key;
// Press the "a" or "A" key (using caps lock or shift) to pop up a prompt message
if
(x ==
"a"
|| x ==
"A"
) {
alert (
You pressed the 'A' key!
);
}
Try it »
Related pages
HTML DOM Reference Manual: key event attribute
HTML DOM Reference Manual: charCode Event Attribute
HTML DOM Reference Manual: which event attribute
Event Object