DHTML Lab - DHTML Diner - NS4/IE4: Using the Keypress Event (2) | WebReference

DHTML Lab - DHTML Diner - NS4/IE4: Using the Keypress Event (2)

DHTML Diner Logo

This is a DHTML cross-browser technique.
The in-page examples will only work in Navigator 4 and Explorer 4, all platforms.

In longer script listings, cross-browser code is blue, Navigator-specific code is red, and Explorer code is green.

All keypresses on this page change the display in the purple-bordered positioned elements on the right.

Using the Keypress Event (2)

In Navigator 4, when the keypress event fires, it creates a which property for the event object to store the Unicode (a.k.a. ASCII) value of the key that was pressed. The event object is passed implicitly to the function called by the event handler, as the function's single argument. Using the recognized standard, we identify this argument as e.

In Explorer 4, the event object is passed explicitly, is identified by the keyword event, and is not a function argument. It has a keyCode property to store the Unicode value of the pressed key.

Using the which/keyCode properties, we can determine which alphanumeric key was pressed. In the following example, we store the Unicode value in the whichASC variable:

function doKey(e) {
    whichASC = (NS4) ? e.which : event.keyCode;
}

String Conversion

JavaScript 1.2 introduced the fromCharCode() method of the String object. It creates a string from an integer or comma-delimited series of integers representing Unicode values:

Syntax:

String.fromCharCode(num1,...,numN)

Example:

String.fromCharCode(65,110,100,121); returns "Andy"

Using fromCharCode(), we can determine which key was pressed in a user-friendly string representation. Most of the time, we will want to process a Y and a y (upper and lower-case) in the same manner. For example, in response to a yes/no question. The letter case may not matter in a user's response. In such instances, we should change all keypresses to lower case, using the toLowerCase() method, before processing.

If you are using a version 4 browser, press any key to see the results in the two bordered elements below.

The doKey() function can now be expanded to reflect the string conversion:

function doKey(e) {
    whichASC = (NS4) ? e.which : event.keyCode;
    whichKey = String.fromCharCode(whichASC).toLowerCase();
}

Finally, let's complete the function by adding the switch statement.



Produced by Peter Belesis and

All Rights Reserved. Legal Notices.
Created: June 05, 1998
Revised: June 05, 1998

URL: http://www.webreference.com/dhtml/diner/keypress/keypress2.html