Using Keyboard Events


document.onkeydown = showKey; 

Keyboard events are not part of DOM Level 1 or Level 2, but are still implemented in recent browsers. Accessing the events differs from the usual approach (window.event in Internet Explorer; the event as the automatic parameter of the function in all other browsers). But then, the keyCode property returns the ASCII code of the key, which can then be processed, as in the following code:

Listening to Keyboard Events (key.html)

done. Christian<script language="JavaScript"   type="text/javascript"> function showKey(e) {   var key;   if (window.event) {     key = window.event.keyCode;   } else {     key = e.keyCode;   }   key = String.fromCharCode(key);   document.getElementById("para").innerHTML += key; } window.onload = function() {   document.onkeydown = showKey; } </script> <p >Click and type here: </p> 

Figure 6.3 shows the result. The keys that are pressed are shown.

Figure 6.3. The key pressed is shown.


Note

All characters in Figure 6.3 are shown in uppercase, since JavaScript always takes into consideration which key was pressed, not whether it was upper- or lowercase. You can, however, also find out whether special keys were pressed by taking a look at the altKey, ctrlKey, and shiftKey properties.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net