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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

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:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

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

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business