What Was Pressed?
After a keyboard event has triggered the associated JavaScript function, the function should recognize the key that was pressed, and react accordingly. But getting there requires another round of browser-incompatibility avoidance.
The information about the keyboard event is passed in the event object, which might be the first parameter of the event handler function, or be stored in the global window.event variable (Internet Explorer). The best way to deal with this inconsistency is by using the following code in your JavaScript event handler:
function keyboardHandler(event) { event = event || window.event; ... rest of the function ... }
The code of the pressed or released key is also stored in incompatible ways. The following table summarizes three of the most common behaviors.
Browser |
keydown/keyup Event |
keypress Event |
Internet Explorer |
The keycode is stored in the event.keyCode property. |
The Unicode character code is stored in event.keyCode property. The keypress event is called only for keys that generate Unicode characters. |
Firefox/Mozilla |
The keycode is stored in the event.keyCode property. |
The keycode is stored in the event.keyCode property. Unicode character code is stored in event.charCode. (This property is set to zero for keys that don’t generate Unicode characters.) The keypress event is called for all keys. |
Opera |
The keycode is stored in the event.keyCode and event.which properties. |
If the key generates a Unicode character, it’s stored in the event.keyCode and event.which properties. If the key doesn’t generate a Unicode character, its keycode is stored in the same properties (and there is no flag to tell you which encoding method is used). |
Although documentation from Microsoft and Mozilla claims that the code stored in the event.keyCode property is the Unicode value of the key pressed, it’s actually the numeric code of the key assigned to various keys by the original Netscape browser. For example, the up-arrow key has the keycode 38 (which corresponds to the Unicode ampersand, &) and the F1 key has the keycode 112 (corresponding to the lowercase p character). To figure out the keycode value of a keyboard key, it’s best to use a small JavaScript program that displays the properties of the keyboard-related event object. A sample is available on my web site. (You can also view its source or download it).
Fortunately, all browsers implement the event properties ctrlKey, altKey, and shiftKey in the same way: They indicate which of the target keys was pressed, giving us means of detecting sequences such as Ctrl-S or Alt-X.