Share this Page URL
Help

Hour 12. Responding to Events > Using Keyboard Events - Pg. 106

Responding to Events Function mousealert(e) whichone = (e.which == message = "You clicked alert(message); } document.onmousedown = { 1) ? "Left" : "Right"; the " + whichone + " button."; mousealert; 106 Using Keyboard Events Prior to the release of Netscape 4.0, JavaScript programs couldn't detect keyboard actions--just mouse actions. This made it difficult to create some types of programs in JavaScript. For example, games were difficult to play using Go Left and Go Right buttons. Thankfully, JavaScript 1.2 and later can detect keyboard actions. The main event handler for this purpose is onKeyPress, which occurs when a key is pressed and released, or held down. As with mouse buttons, you can detect the down and up parts of the keypress with the onKeyDown and onKeyUp event handlers. Of course, you may find it useful to know which key the user pressed. You can find this out with the event object, which is sent to your event handler when the event occurs. The event.which prop- erty stores the ASCII character code for the key that was pressed. Note ASCII (American Standard Code for Information Interchange) is the standard numeric code used by most computers to represent characters. It assigns the numbers 0-128 to various characters--for example, the capital letters A through Z are ASCII values 65 to 90. If you'd rather deal with actual characters, you can use the fromCharCode string method to convert it. This method converts a numeric ASCII code to its corresponding string character. For example, the following <body> tag includes an event handler that displays the character for the key that was pressed in an alert message: <body onKeyPress="window.alert('You pressed:' + String.fromCharCode(event.which));" This statement uses the String.fromCharCode method to convert the event.which property to a string, and then displays the string as part of an alert dialog. Using the onLoad Event Another event you'll use frequently is onLoad. This event occurs when the current page (including all of its images) finishes loading from the server. The onLoad event is related to the document object, and to define it you use an event handler in the <BODY> tag. For example, the following is a <BODY> tag that uses a simple event handler to display an alert when the page finishes loading: <body onLoad="window.alert('Loading complete.');"> Note Since the onLoad event occurs after the HTML document has finished loading and dis- playing, you cannot use the document.write or document.open statements within an onLoad event handler. This would overwrite the current document. JavaScript includes a variety of other events. Many of these are related to forms, which you'll learn more about in Hour 14. Another useful event is onError, which you can use to prevent error mes- sages from displaying. This event is described in Hour 21, "Finding and Handling Errors."