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:

  1. Read the virtual key code from the operating system's event information, if such information is available.
  2. If an Input Method Editor is processing key input and the event is keydown, return 229.
  3. If input key when pressed without modifiers would insert a numerical character (0-9), return the ASCII code of that numerical character.
  4. 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.
  5. 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.
  6. 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.
  7. Return the virtual key code from the operating system.
  8. If no key code was found, return 0.

How to calculate keyCode for keypress events

The keyCode for keypress events is calculated as follows:

  1. If the implementation supports a 'conflated model', set keyCode to the Unicode code point of the character being entered.
  2. 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 keyvirtual key code
Backspace8
Tab9
Enter13
Shift16
Control17
Alt18
Caps Lock20
Escape27
Space32
Page up33
Page down34
End35
Home36
Left37
Up38
Right39
Down40
Delete46

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:

The keyvirtual key code
Semicolon (;)186
Colon (:)186
Plus (+)187
Equals sign (=)187
Comma (,)188
Less than sign (<)188
Minus (-)189
Underscore (_)189
Period (.)190
Greater than sign (>)190
Question mark (?)191
Forward slash (/)191
Backtick (`)192
Tilde (~)192
Opening square bracket ([)219
Opening curly bracket ({)219
Backslash (\)220
Pipe (|)220
Closing square bracket (])221
Closing curly bracket (})221
Single quote (')222
Double quote (")222

Acknowledgements

Thanks to Anne van Kesteren, Alexey Proskuryakov, Olli Pettay, Bjoern Hoehrmann and Oliver Hunt for comments on earlier (and more complicated) versions of this draft.