October 24, 1999 - Keyboard-Triggered Events | WebReference

October 24, 1999 - Keyboard-Triggered Events

Yehuda Shiran October 24, 1999
Keyboard-Triggered Events
Tips: October 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

There are two basic ways to interact with the user. The common way is through the mouse and the onClick event. Another way to interact with an application is through the keyboard. The advantage of the keyboard interface is that it includes over a hundred different key variations, and each may have a different role in controlling the application. The event handler of a key press is onKeyPress. In our Snakes game we used the numeric key pad to control the snake's movement. The onKeyPress event handler is specified in the <BODY> tag:

<BODY onKeyPress="handlePress(event)">

The handlePress() function gets the event object and reads the pressed character from it:

function handlePress(e) {
  var whichCode = (window.Event) ? e.which : e.keyCode;
  alert("You have pressed the character " + String.fromCharCode(whichCode));
}

Notice how we detect the browser type. The window object features the Event property in Navigator 4.0x and above. As you can see from the preceding script, each browser holds the code of the pressed key in a different property. Navigator saves it in the event object's which property while Internet Explorer puts it in the its keyCode property. We use the fromCharCode() method to convert the ASCII value of the pressed character to the character itself. Refer to Column 11, The Cross-Browser Event Model, for more information about cross-browser event handling.