CodingBison

In this section, we cover the last set of events: the keyboard events. We begin by providing them in the table below.


Table: Keyboard Events
EventDescription
onkeypresswhen we press a key.
onkeydownfires before we press a key.
onkeyupfires when we release a previously pressed key.

In the above table, the onkeypress event fires when we press any key on the keyboard. The onkeydown event fires when we press the key down. And the onkeyup event fires when we release a previously pressed key. We should mention that all of the events are cancellable and all of the events bubble.

Here is a simple implementation that attaches handlers to the above three keyboard events. The handlers simply print a message on the screen when the associated event occurs.

 <!doctype html>
 <html>
 <head> <h2> A Trivial Page </h2></head>
 <body> 
 <div id="idDiv"></div>
 <script type="text/javascript">
 var elem; // Global Variable.

 function printOnkeypress() {elem.innerHTML += "Key Press<br>";}
 function printOnkeydown() {elem.innerHTML += "key Down<br>";}
 function printOnkeyup() {elem.innerHTML += "Key Up<br>";}

 function addThisEvent(obj, eventType, eventHandler, capturingType) {
     var newEventType = "on" + eventType;
     if (obj.addEventListener) {
         obj.addEventListener(eventType, eventHandler, capturingType);
     } else if (obj.attachEvent) {
         obj.attachEvent(eventType, eventHandler);
     } else if (obj[newEventType]) {
         obj[newEventType] = eventHandler;
     }
 }

 window.onload = ( function() {
     elem = document.getElementById("idDiv");
     elem.innerHTML += "Page has loaded<br>";

     addThisEvent(window, "keypress", printOnkeypress, false); 
     addThisEvent(window, "keydown", printOnkeydown, false); 
     addThisEvent(window, "keyup", printOnkeyup, false); 
 });
 </script>
 </body>
 </html>

And here is the browser output when we press a key couple of times.



Figure: Keyboard Events





comments powered by Disqus