Keyboard Events

The keydown and keyup events are fired when the user presses or releases a key on the keyboard. They are generated for modifier keys, function keys, and alphanumeric keys. If the user holds the key down long enough for it to begin repeating, there will be multiple keydown events before the keyup event arrives.

The event object associated with these events has a numeric keyCode property that specifies which key was pressed. For keys that generate printable characters, the keyCode is generally the Unicode encoding of the primary character that appears on the key. Letter keys always generate uppercase keyCode values, regardless of the state of the Shift key since that is what appears on the physical key. Similarly, number keys always generate keyCode values for the digit that appears on the key, even if you are holding down Shift in order to type a punctuation character. For nonprinting keys, the keyCode property will be some other value. These keyCode values have never been standardized, but reasonable cross-browser compatibility is possible, and Example 17-8 includes a mapping from keyCode values to function key names.

Like mouse event objects, key event objects have altKey, ctrlKey, metaKey, and shiftKey properties, which are set to true if the corresponding modifier key is held down when the event occurs.

The keydown and keyup events and the keyCode property have been in use for more than a decade but have never been standardized. The DOM Level 3 Events draft standard ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.