Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

key event attribute

key event attribute

Event Object Reference Event Object

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:

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.

 可能值:     
  • A single letter (such as "a", "W", "4", "+" or "$")
  • Multiple letters (such as "F1", "Enter", "HOME" or "CAPS LOCK")
  • **Note:** Chrome, Safari and Opera browsers return undefined | | --- | --- | | DOM version: | DOM Level 3 Events |

    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 Reference Event Object