The onkeydown , onkeypress , and onkeyup EventsAs you can guess, you use the onkeydown , onkeypress , and onkeyup events to handle keystrokes. You can find the support for these events in Table 6.72. Table 6.72. The onkeydown , onkeypress , and onkeyup Events
Form input controls such as text fields handle keystrokes by themselves ; if you want to create your own key-handling routines, however, you can use these events. We'll cover this in more detail in Chapter 15, because it gets a little complex. For example, there are two types of codes: key codes and character codes . There is one key code for each key on the keyboard, and it'll be the same even if modifier keys, such as the Shift key, were also pressed. Character codes, on the other hand, correspond to the Unicode code for a character and include capital and small characters . Here are the three keystroke events, the order in which they occur, and what they do:
When you're handling alphanumeric keys, use onkeypress ; when you're handling nonalphanumeric keys (such as arrow keys), use onkeydown and/or onkeyup . In onkeydown and onkeyup , modifiers such as the Shift key haven't been applied to the key yet, and you have to check properties such as event.shiftKey yourself (see Table 6.2) to see whether a character should be capitalized. Note that the character codes and key codes you get are just numbersyou still have to translate them into characters. Here's an example that reads keys in both browsers using the <BODY> element's ONKEYPRESS attribute and displays what you've typedjust load this page and type something (don't give the focus to the text field); the keys you type will be inserted into the text field automatically: (Listing 06-17.html on the web site)<HTML> <HEAD> <TITLE>Reading Keys</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- document.onkeypress = keyPress var instring = "" function keyPress(e) { if(navigator.appName == "Netscape") { if(parseInt(navigator.appVersion) == 4) { instring += unescape("%" + e.which.toString(16)) document.form1.text1.value = instring } if(parseInt(navigator.appVersion) > 4) { instring += unescape("%" + e.charCode.toString(16)) document.form1.text1.value = instring } } if (navigator.appName == "Microsoft Internet Explorer") { instring += String.fromCharCode(window.event.keyCode) document.form1.text1.value = instring } } // --> </SCRIPT> </HEAD> <BODY> <H1>Reading Keys Directly (Type some text!)</H1> <BR> <FORM NAME="form1"> <INPUT NAME="text1" TYPE="TEXT" SIZE="20"> </FORM> </BODY> </HTML> You can see the results in Figure 6.13more on this code in Chapter 15. Figure 6.13. Using the onkeypress event.
Tip If you want to cancel a keystroke in the Internet Explorer 4+, set the event.returnValue property to false in the keystroke event handlers. |