DHTML Lab - DHTML Diner - NS4/IE4: Using the Keypress Event (3) | WebReference

DHTML Lab - DHTML Diner - NS4/IE4: Using the Keypress Event (3)

DHTML Diner Logo

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.

Press any underlined letter to toggle related checkbox value:

Favorite Reading:
 Mystery
 Science Fiction
 Romance
 Adventure
 Comics
 Cereal Boxes

Statements used:

fK = document.fmKeys;
switch (whichKey) {
 case "m":
   fK.mys.checked =
    !fK.mys.checked;
   break;
 case "s":
   fK.sci.checked =
    !fK.sci.checked;
   break;
 case "r":
   fK.rom.checked =
    !fK.rom.checked;
   break;
 case "a":
   fK.adv.checked =
    !fK.adv.checked;
   break;
 case "c":
   fK.com.checked =
    !fK.com.checked;
   break;
 case "b":
   fK.cer.checked =
    !fK.cer.checked;
   break;
 default:
   break;
}

Using the Keypress Event (3)

We introduced the JavaScript 1.2 switch statement in column 19. It is particularly suited to keypress handling, since we can simply list our "hot" keys in a lookup-table-like fashion, and use the default: label for any non-"hot" key processing.

function doKey(e) {
  whichASC = (NS4) ? e.which : event.keyCode;
  whichKey = String.fromCharCode(whichASC).toLowerCase();
  switch (whichKey) {
    case "a":
      doA();
      break;
    case "b":
      doB();
      break;
    case "1":
      location.href = "page1.html";
      break;
    case "2":
      location.href = "page2.html";
      break;
    case "y":
      alert('You answered "Yes"')
      break;
    case "n":
      alert('You answered "No"')
      break;
    default:
      break;
  }
}

In the example above, we have defined statements to be executed whenever a, b, y, and n (regardless of case) and 1 and 2 are pressed.

Notice that upon keypress, we may choose to execute a function, navigate to a new page, or display an alert window. Any normal JavaScript statements may be included. In this page's live example (left column), keypresses toggle the state of form checkboxes.

On the next page, a quick review of the code necessary for using the keypress event.



Produced by Peter Belesis and

All Rights Reserved. Legal Notices.
Created: June 05, 1998
Revised: June 05, 1998

URL: http://www.webreference.com/dhtml/diner/keypress/keypress3.html