Examining Mouse Buttons and Key Codes

The next code listing, Example 6.3, further demonstrates how to access event object properties in both browsers, even when the properties don’t match up well. In this case, a script displays information about mouse clicks and key presses in the status bar, to limit the disruption of the user. For mouse clicks over a button, this laboratory application presents the identifying integer for the mouse button used to do the click. For key presses in a text area, the application displays the character code value of the key typed by the user.

Example 6-3. Looking for Mouse Button and Keyboard Character Codes

<HTML> <HEAD> <TITLE>Button Codes / Key Codes</TITLE> <SCRIPT LANGUAGE="JavaScript"> var isNav, isIE if (parseInt(navigator.appVersion) >= 4) { if (navigator.appName == "Netscape") { isNav = true } else { isIE = true } } function showBtnOrKey(evt) { var theBtnOrKey if (isNav) { theBtnOrKey = evt.which } else { if (window.event.srcElement.type == "textarea") { theBtnOrKey = window.event.keyCode } else if (window.event.srcElement.type == "button") { theBtnOrKey = window.event.button } } status = theBtnOrKey return false } </SCRIPT> </HEAD> <BODY> <H1>Mouse Button and Key Codes from Event Objects</H1> <HR> <FORM> <P>Click on this <INPUT TYPE="button" VALUE="Button" onClick="showBtnOrKey(event)"> with either mouse button (if you have more than one).</P> <P>Enter some text with uppercase and lowercase letters:<BR> <TEXTAREA COLS=30 ROWS=4 onKeyPress="showBtnOrKey(event)" ...

Get Dynamic HTML: The Definitive Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.