HTML and CSS Reference
In-Depth Information
EXAMPLE 13.25
<html>
<head><title>keypress event</title>
1
<script type="text/javascript" src="browser_info.js" ></script>
</head>
2
<body onKeyPress ="
3
if(browserName == 'Firefox' ){
4
alert('The key pressed:'+ event.which +
5
' ASCII= '+ String.fromCharCode(event.which));
}
6
else if(browserName == 'Microsoft Internet Explorer' ||
browserName== 'Opera' ){
alert('The key pressed:'+ event.keyCode +
' ASCII='+ String.fromCharCode(event.keyCode));
}
">
<font face = "verdana">
<b>Press any key on your keyboard and see what happens!</b>
</font>
</body>
</html>
EXPLANATION
1
An external file is loaded here. It contains the code to determine what browser is
being used. See http://www.JavaScripter.net/faq/browsern.htm for source code .
2
The body tag is assigned an onKeyPress event handler. If the user presses a key
anywhere in the body of the document, the event is triggered, causing an alert
method to appear and display the value of the key.
3
First we check to see if the browser being used is Firefox. Firefox and Internet Ex-
plorer use different properties to describe the numeric value of the key being
pressed.
4
The which property of the event object describes the numeric ASCII value for the
key that was pressed. (See more of the event object on page 499.)
5
The String method fromCharCode() converts the ASCII value of the key to the
character value that is shown on the key (e.g., ASCII 65 is character “A”).
6
If the browser isn't Firefox, the alternative for this example is Internet Explorer or
Opera. They use the keyCode property to represent the numeric value of the key
being pressed. The fromCharCode() String method converts the number to a char-
acter. The output is displayed for both browsers in Figures 13.42 and 13.43.
Search WWH ::




Custom Search