As 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.
<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> |