The Navigator Event Model: New Mouse Click Events - Doc JavaScript | WebReference

The Navigator Event Model: New Mouse Click Events - Doc JavaScript


New Keyboard Events

JavaScript 1.2 introduces several new keyboard events:

Rather than having a single event for a key press, there are three different events to choose from. A keypress event occurs when you press or hold down a key. This event is actually a combination of two separate actions: the key reaching the bottom of its physical travel (keydown), and the instant at which the key starts its travel upward (keyup).

Thanks to the event.which property, you can even find out what key was pressed:

<SCRIPT LANGUAGE="JavaScript">
<!--
function processKeypresses(e) {
  var whichASC = e.which; // key's ASCII code
  var whichChar = String.fromCharCode(whichASC); // key's character
  if (whichChar == 'A' || whichChar == 'a')
    window.scrollBy(0, 10); // scroll down
  else if (whichChar == 'Z' || whichChar == 'z')
    window.scrollBy(0, -10); // scroll up
  return false; // cancel event otherwise
}
if (document.captureEvents)
  document.captureEvents(Event.KEYPRESS);
document.onkeypress = processKeypresses;
// -->
</SCRIPT>

Notice the use of the String.fromCharCode() method to convert an integer to a character with that ASCII value. This is required because the which property holds the ASCII value of the key that was pressed.

To experiment with this script, click the "a" and "z" keys. The window should scroll up and down, respectively. Now hold down one of these keys and the window will scroll smoothly. The function always returns false. This cancels all keypress events, so you can't use the keyboard to enter text in a form field, for example.

Remember that this script works only with Netscape Navigator 4.0x and above. It will not work on older versions of Netscape Navigator, and will generate an error on Microsoft Internet Explorer 4.0x.

For a good demonstration of keyboard events, check out Peter Belesis' column on "Using the Keypress Event."

http://www.internet.com


Created: December 16, 1997
Revised: December 16, 1997

URL: http://www.webreference.com/js/column9/newkeyboardevents.html