This is a DHTML cross-browser technique.
The in-page examples will only work in Navigator 4 and Explorer 4, all platforms. In longer script listings, cross-browser code is blue, Navigator-specific code is red, and Explorer code is green. Question: Do you have a quick technique you would like to see covered in DHTML Diner? Answer by pressing Y or N.
Statements used:
switch (whichKey) {
case "y":
mess =
"Great, send it along!"
break;
case "n":
mess =
"Oh, come on. You must!"
break;
default:
mess =
"You must press Y or N!"
}
alert(mess)
|
|
Using the Keypress Event (4)
Step-by-Step
1. Include this script in your page:
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
IE4 = (document.all);
NS4 = (document.layers);
if (NS4) document.captureEvents(Event.KEYPRESS);
document.onkeypress = doKey;
function doKey(e) {
whichASC = (NS4) ? e.which : event.keyCode;
whichKey = String.fromCharCode(whichASC).toLowerCase();
switch (whichKey) {
case "a":
...statements to execute if "a" is pressed...
break;
case "b":
...statements to execute if "b" is pressed...
break;
case "1":
...statements to execute if "1" is pressed...
break;
case "2":
...statements to execute if "2" is pressed...
break;
case "y":
...statements to execute if "y" is pressed...
break;
case "n":
...statements to execute if "n" is pressed...
break;
.
. other alphanumeric "hot" keys
.
default:
...statements to execute if no "hot" key is pressed...
or include the break statement:
break;
}
}
//-->
</SCRIPT>
2. Define your "hot" keys as strings in the switch statement's case labels, as in the example above.
3. In each case label, place the appropriate JavaScript statements to be executed when that key is pressed. End statement list with a break.
4. Optionally, define a default behavior in case the key pressed is not "hot", in the default: label.
5. If the hot keys are case-sensitive, omit the toLowerCase() method when declaring whichKey, and define different statements for upper and lower case characters.
|