HTML and CSS Reference
In-Depth Information
13.7.6 Key Events
The Handlers. As of JavaScript 1.2, keyboard actions, not just mouse actions, can be
detected in JavaScript programs. Now that we have discussed the event object, we will
look at how to detect keyboard actions. This is useful, for example, in creating widgets
or certain types of game programs where keyboard entry must be detected to determine
the next action. The onKeyPress, onKeyDown , and onKeyUp event handlers are triggered
when the user presses a key and releases it. The onKeyPress event is a combination of
two actions: After you press down on the key, the event happens just at the point you
release it. The other two key events happen as soon as you press a key down ( onKey-
Down ) and then when you release it ( onKeyUp ). The onKeyDown and onKeyPress events
keep firing continuously as long as the user keeps a key depressed, whereas the onKeyUp
event fires once when the user releases the key. Detecting a user's keystrokes might give
you problems as all browsers are not compatible in how they handle the keys and the
event properties.
Properties for the key Event. The two main properties for the key event are key-
Code and charCode . The keyCode property describes the actual key that was pressed, for
example, the B key. The charCode property provides the ASCII value for that key. If it is
a lowercase b, it will return 98 and if it is an uppercase B, it will return 66. The problem
is that Windows Internet Explorer and Opera do not support charCode , but they do sup-
port keyCode when the onKeyPress event is triggered. For tables showing which brows-
ers support these properties and a selection of other tables dealing with punctuation
keys, special keys, and so on, see http://www.quirksmode.org/js/keys.html .
Browser Incompatibilities. Figures 13.40 and 13.41 were taken from a site where a test
can be run from your browser by performing keystrokes. The output shows what properties
are supported for keydown, keypress, keyup, and so on. Go to http://unixpapa.com/js/test-
key.html to run the test. Go to http://www.JavaScriptkit.com/jsref/eventkeyboardmouse.shtml for
an excellent reference with examples.
 
 
Search WWH ::




Custom Search