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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
OpenOffice 3.2 Lands Amid Critical Changes
Red Hat, IBM Firmly in KVM Virtualization Camp
Red Hat Talks Up Open Source Cloud Plans

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.


People who read this tip also read these tips:

Look for similar tips by subject:


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Search Engine Optimization: Selecting and Embedding Keywords · Are Google's Language Translation Web Services Ready for Prime Time? · Installing and Using Meeplace, the Business Review CMS
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
IBM DB2 10 for z/OS: Justifying the Upgrade · Living La Vida Colo: Choosing the Right Colocation Facility · FTC Concerns over Social Media Privacy Linger