keyCode property of key events

Event models

An implementation may choose to expose both virtual key codes and character codes in the keyCode property ('conflated model'), or report separate keyCode and charCode properties ('split model').

How to calculate keyCode for keydown and keyup events

The keyCode for keydown / keyup events is calculated as follows:

Read the virtual key code from the operating system's event information, if such information is available.

If an Input Method Editor is processing key input and the event is keydown, return 229.

If input key when pressed without modifiers would insert a numerical character (0-9), return the ASCII code of that numerical character.

If input key when pressed without modifiers would insert a a lower case character in the a-z alphabetical range, return the ASCII code of the upper case equivalent.

If the implementation supports a key code conversion table for the operating system and platform, look up the value. If the conversion table specifies an alternate virtual key value for the given input, return the specified value.

If the key's function, as determined in an implementation-specific way, corresponds to one of the keys in the table of fixed virtual key codes, return the corresponding key code.

Return the virtual key code from the operating system.

If no key code was found, return 0.

How to calculate keyCode for keypress events

The keyCode for keypress events is calculated as follows:

If the implementation supports a 'conflated model', set keyCode to the Unicode code point of the character being entered.

If the implementation supports a 'split model', set keyCode to 0.

Fixed virtual key codes

The virtual key codes for the following keys do not usually change with keyboard layouts on desktop systems:

The key

virtual key code

Backspace

8

Tab

9

Enter

13

Shift

16

Control

17

Alt

18

Caps Lock

20

Escape

27

Space

32

Page up

33

Page down

34

End

35

Home

36

Left

37

Up

38

Right

39

Down

40

Delete

46

Optionally fixed virtual key codes

This section is informative

The following punctuation characters may change virtual codes between keyboard layouts, but reporting these values will likely be more compatible with legacy content expecting US-English keyboard layout: