Home > Articles > Programming > User Interface (UI)

  • Print
  • + Share This
Like this article? We recommend

Keyboard Events

Keyboard events are the most troublesome JavaScript events today. Not only is Internet Explorer implementation of JavaScript events different from everyone else’s, but the event specification of the Document Object Model (DOM) doesn’t provide a keyboard event module, leaving browser vendors on their own—and giving web developers a huge headache.

Luckily, the majority of the browser vendors decided to implement keyboard events in a somewhat compatible manner:

  • There are three keyboard-related events: keydown, keyup, and keypress.
  • You can register event handlers by using the onkeydown, onkeyup, and onkeypress properties of DOM objects, or by using the addEventListener DOM function (even if you’re using non-DOM events).
  • The fields in the keyboard-related event object are similar (although the event object itself is accessed in various ways).

The keydown event is triggered (in all browsers) whenever any keyboard key (including Ctrl, Shift, Alt, function keys, or arrow keys) is pressed. The keydown event usually is followed by the keypress event:

  • Gecko-based browsers (including Mozilla and Firefox) treat the keypress event as equivalent to the keydown event. Both are triggered at the same time regardless of the pressed key; the only difference between them is the field values in the event object.
  • Internet Explorer triggers the keypress event only for keys that generate character (Unicode) values. If the event propagation is disabled in the keydown event, the keypress event is not generated.
  • The keyup event is triggered whenever a keyboard key is released.
  • + Share This
  • 🔖 Save To Your Account