12.7 Handling Key Events: onKeyPress, onKeyDown , and onKeyUpAs of JavaScript 1.2, keyboard actions, not just mouse actions, can be detected in JavaScript programs. This is useful, for example, in 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 ( onKeyDown ) 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. Some browsers may differ in the way they handle key events. Example 12.19<html><head><title>Key Events</title></head> 1 <body bgcolor="yellow" onKeyPress = " 2 if( navigator.appName=='Netscape' ) 3 alert('The key pressed:'+ event.which + 4 'ASCII'+ String.fromCharCode(event.which) ) else 5 alert('The key pressed:'+ event.keyCode + 'ASCII'+ String.fromCharCode(event.keyCode) );"> <font face = "verdana"> <b>Press any key on your keyboard and see what happens!</b> </body> </html> EXPLANATION
Example 12.20<html> <head><title>Key Events</title> </head> <body bgcolor="white"><font face="arial"> <center><img src="key.gif"></center> <center><b><h2>Events</h2> <h3> <br>A <font color="blue">blue </font>bouncing arrow will appear when you press a key down<br>and a <font color="red">red</font> jumping arrow appears when you release the key<br></b> 1 <form> Type something in the box: 2 <input type="text" size=10 3 onKeyDown="document.Arrow.src='images/down_arrow.gif'" 4 onKeyUp="document.Arrow.src='images/up_arrow.gif'"> <input type=reset value="reset"> </form> 5 <img src="images/up_arrow.gif" name="Arrow"> </body></html> EXPLANATION
![]() |