Keyboard events (Definition)

Some events within the event-handling complex of a browser are related to keyboard handling.

The following events relate to keyboard handling:

These events are classified as keyboard events because they are generated as a result of user interactions with the keyboard.

Note that the onKeyPress event is triggered as a result of a matching pair of onKeyDown and onKeyUp events. You should not rely on the events arriving in any particular order, although onKeyPress probably arrives before onKeyUp.

For example, as a key is pressed, an onKeyDown event is fired. As it is released, an onKeyUp event and an onKeyPress event are fired. An onKeyPress is only fired once for each onKeyDown and onKeyUp pair.

In Netscape, you can capture keyboard events by calling the captureEvents() method like this:


This need not necessarily apply to the window; the area of interest can be more limited by selecting an appropriate object.

Example code:

   <!-- Event programming example supplied by Alex.Abacus -->
   <SCRIPT LANGUAGE="JavaScript1.2">
   // Object sensing routine
   var isNN4up = (window.Event)? true : false;
   // Key press handler designed for cross platform use
   function key_press_event_handler(e)
      if (isNN4up)
         var whichKey = e.which;
         var whichKey = window.event.keyCode;
      var realKey = String.fromCharCode(whichKey);
      window.status = 'You pressed ' + realKey +
      ' (Key code: ' + whichKey + ')'
   // Register event handler for Netscape
   if (isNN4up)
   // Register event handler for MSIE
   document.onkeypress = key_press_event_handler;

See also:captureEvents(), Event, Event names, Event type constants, Event.modifiers, Event.which, onKeyDown, onKeyPress, onKeyUp, String.fromCharCode()