Working With JavaScript Events

Introduction

 
This article explains event handling in JavaScript. Prior to starting anything, I will say that I'm assuming the reader is familiar with the basic syntax of JavaScript and jQuery. In this article, I will cover mouse and keyboard events. These are the major events used in web sites. So let's start.
 

Defining the event

 
An event is any condition arising due to a change in the state of an element. That change can be introduced in various ways, like interacting with web pages, for instance clicking on a button. Events can also be raised programmatically but it is used only in specific cases and its not supported in all browsers. In general use, most of the events are generated by the interaction of the user with the web page. Whenever an event is fired, the code to handle that event is executed. That code can be the default one as in an anchor tag click event or it can be user-defined.
 

How do events work?

 
Before getting into how they work let's understand first what an event handler is. An event handler is responsible for handling an event and it is just code that is bound to any element. Whenever the user interacts with an element, that element checks whether there is an event handler bound to it. If there is then that event handler will be executed otherwise not. To understand better, let us use the example of clicking on a button and then a menu or data or a new page is shown. Why does this happen?
 
The reason is that when you click the button, the button generates an event, say a click event and when this event is fired it will check for the handler and the handler code is executed. It is basically a handler that processes the events or handles them and shows some relevant information to the user. Now the question is, how does the element check for an event handler? This is called event ordering. For that, we have two approaches and both are the opposite of each other. The one is similar to a top-down approach called event capturing and it is used less often. In this technique, the checking starts from the outermost element which is HTML and moves toward the original source (inward/downward). For example, check the following code:
  1. <html>  
  2.     <body onclick="dosomework()">  
  3.         <div onclick="dosomework()"></div>  
  4.     </body>  
  5. </html> 
    Here if the user clicks on the button then first the HTML element is checked then the body element and at last the div tag handler will be executed. It is not required in most cases. The other technique is the bottom-up approach or event bubbling. In this technique, the target node is checked first and then the event is bubbled up to the parent element until it reaches the HTML element.
     

    Evolution of events

     
    In earlier days we generally had small problems and code but as web sites progressed the sites became more complex. Earlier we used to write JavaScript in this way:
    1. <div onclick="alert('i'm script')"></div> 
    But now we can't write the entire JavaScript in one line. So we separate it into a "script" section. But that was also not enough. That technique separated the script and HTML but there was no solution for dynamic event addition and removal. As the web progressed, the compelling need for addition and removal leads to the birth of a new way of applying event handling on elements. That way was:
    1. Document.getElementById("e1").addEventListener("click", myFunction, false); 
    "addEventListener" is a function to add an event listener to an element. The first parameter is the name of the event to be monitored. The second parameter is the event handler code and the third and the last parameter specifies whether the element should use event bubbling or not.
     
    The counterpart of this function is "removeEventListener" with the following syntax:
    1. removeEventListener("click", myFunction); 
    The first parameter is the event name to remove and the second is the handler name attached to that event.
     

    Event control

     
    To control the event from executing we have various functions like:
    1. e.preventDefault() 
    It cancels the default action of the event.
    1. e.cancelBubble=true/false 
    It is used for enabling or disabling the event propagation.
    1. e.stopPropogation() 
    It is also used for stopping the event propagation or event bubbling effect.
     
    Note on Event(e) object of JavaScript
     
    Whenever an event is fired, the event object is created first and it is passed to the event handler. That event object contains many details related to that particular object. It's an interface and it has various subclasses. You can check more here.
     
    Working Example of Event Handling
     
    In this example, I'll cover all three ways of registering an event to an element and most importantly how to detect a specific event and key.
     
    For this example to work first we need a sample HTML file like this:
    1. <html>  
    2. <head>  
    3.     <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.min.css"rel="stylesheet" type="text/css" />  
    4.     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>  
    5.     <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>  
    6.     <meta charset="utf-8" />  
    7.     <title>Event Handling</title>  
    8.       <style>  
    9.         /* we will use this section for adding css classes */  
    10.     </style>  
    11.  </head>  
    12. <body>  
    13.       <script>  
    14.         $(document).ready(function () {  
    15.             // We will use this for adding our jQuery  
    16.         });  
    17.     </script>  
    18. </body>  
    19. </html> 
    Let's start
     
    Now first paste this snippet into HTML:
    1. Select what you want to block :  
    2. <select id='i1' onchange="block();">  
    3. <option >Ctrl </option>  
    4. <option >alt </option>  
    5. <option >Ctrl+Shift </option>  
    6. <option >F12 </option>  
    7. <option >Right Click</option>  
    8. <option >F5</option>  
    9. <option >Left Click</option>     
    10. <option >Middle Click</option>     
    11. <option >Numbers</option>  
    12. <option >Characters</option>  
    13. <option >Special Characters</option>  
    14. </select> 
    What we did is just create a combo box for selecting various events for the demo. The first line of the code shows one way of adding an event on an element.  
     
    Add this HTML code snippet:
    1. <div id='dlg'>  
    2.       <div>Message</div>  
    3.       <div id='msg'>Message will appear here</div>  
    4.     </div> 
    This snippet basically creates an output window for our demo.
     
    Now add this css for styling purpose only
    1. #dlg{  
    2.   border:1px solid #1245aa;  
    3.   width:auto;  
    4.   height:auto;  
    5.   box-shadow:0px 0px 250px #45ab45;   
    6.   display:none;  
    7. }  
    8. #msg{  
    9.    width:auto;  
    10.   height:auto;  
    11.   box-shadow:0px 0px 20px #45aff5;     

    It will provide our output window a good shadow effect.
     
    It's time to code, to register an event and create an event handler. For that copy the following code into your script section:
    1. function block() {  
    2.     var keyblock = document.getElementById('i1').selectedIndex;  
    3.     removeAllLis();  
    4.     switch (keyblock) {  
    5.         case 0:  
    6.             ctrlBlk = function (e) {  
    7.                 if (e.ctrlKey) {  
    8.                     showMsg("Control key blocked!");  
    9.                     e.preventDefault();  
    10.                 }  
    11.             };  
    12.             document.addEventListener("keydown", ctrlBlk);  
    13.             break;  
    14.         case 1:  
    15.             altBlk = function (e) {  
    16.                 if (e.altKey) {  
    17.                     showMsg("Alt key blocked!");  
    18.                     e.preventDefault();  
    19.                 }  
    20.             };  
    21.    
    22.             document.addEventListener("keydown", altBlk);  
    23.             break;  
    24.         case 2:  
    25.             ctrlShiftBlk = function (e) {  
    26.                 if (e.ctrlKey && e.shiftKey) {  
    27.                     showMsg("Ctrl + Shift key blocked!");  
    28.                     e.preventDefault();  
    29.                 }  
    30.             };  
    31.             document.addEventListener("keydown", ctrlShiftBlk);  
    32.             break;  
    33.         case 3:  
    34.             F12blk = function (e) {  
    35.                 if (e.keyCode == 123) {  
    36.                     showMsg("F12 key blocked!");  
    37.                     e.preventDefault();  
    38.                 }  
    39.             };  
    40.             document.addEventListener("keydown", F12blk);  
    41.             break;  
    42.         case 4:  
    43.             rtclkblk = function (e) {  
    44.                 if (e.which == 3) {  
    45.                     showMsg("right click blocked!");  
    46.                     e.preventDefault();  
    47.                 }  
    48.             };  
    49.             document.addEventListener("mousedown", rtclkblk);  
    50.             break;  
    51.    
    52.         case 5:  
    53.             f5blk = function (e) {  
    54.                 if (e.keyCode == 116) {  
    55.                     showMsg("F5 Key blocked! No more refresh :D");  
    56.                     e.preventDefault();  
    57.                 }  
    58.             };  
    59.             document.addEventListener("keydown", f5blk);  
    60.             break;  
    61.         case 6:  
    62.             leftclickblk = function (e) {  
    63.                 if (e.which == 1) {  
    64.                     showMsg("Left click blocked!");  
    65.                     e.preventDefault();  
    66.                 }  
    67.             };  
    68.             document.addEventListener("mousedown", leftclickblk);  
    69.             break;  
    70.         case 7:  
    71.             middleclickblk = function (e) {  
    72.                 if (e.which == 2) {  
    73.                     showMsg("middle click blocked!");  
    74.                     e.preventDefault();  
    75.                 }  
    76.             };  
    77.             document.addEventListener("mousedown", middleclickblk);  
    78.             break;  
    79.         case 8:  
    80.             numbersblk = function (e) {  
    81.                 if (e.keyCode >= 96 && e.keyCode <= 105 || e.keyCode >= 48 && e.keyCode <= 57) {  
    82.                     showMsg("Number keys blocked!");  
    83.                     e.preventDefault();  
    84.                 }  
    85.             };  
    86.             document.addEventListener("keydown", numbersblk);  
    87.             break;  
    88.         case 9:  
    89.             charblk = function (e) {  
    90.                 if (e.keyCode >= 65 && e.keyCode <= 90) {  
    91.                     showMsg("Character keys blocked!");  
    92.                     e.preventDefault();  
    93.                 }  
    94.             };  
    95.             document.addEventListener("keydown", charblk);  
    96.             break;  
    97.         case 10:  
    98.             spcharblk = function (e) {  
    99.                 if (e.keyCode >= 186 && e.keyCode <= 222) {  
    100.                     showMsg("Special Character key blocked!");  
    101.                     e.preventDefault();  
    102.                 }  
    103.             };  
    104.             document.addEventListener("keydown", spcharblk);  
    105.             break;  
    106.         default: alert("wait");  
    107.    
    108.     }  
    109.    
    110. }  
    111.    
    112. function removeAllLis() {  
    113.     try {  
    114.         document.removeEventListener('keydown', altBlk);  
    115.         document.removeEventListener('keydown', ctrlBlk);  
    116.         document.removeEventListener('keydown', ctrlShiftBlk);  
    117.         document.removeEventListener('keydown', F12blk);  
    118.         document.removeEventListener('keydown', f5blk);  
    119.         document.removeEventListener('mousedown', rtclkblk);  
    120.     } catch (err) {  
    121.     }  
    122. }  
    123. function showMsg(msg) {  
    124.     $("#msg").text(msg);  
    125.     $('#dlg').dialog({  
    126.         show: {  
    127.             effect: "bounce",  
    128.             duration: 500  
    129.         },  
    130.         hide: {  
    131.             effect: "blind",  
    132.             duration: 2000  
    133.         }  
    134.     });  

      What we are doing in the code above is basically registering the event when it is chosen in the combo box and removing it on the new selection. The block() function will be called each time to block the selected option whenever the selection is changed. The removeAllLis() function is used for removing the listeners once they are used. Line 2 is used to get the current selection of the combo box. In each case statement, we are registering the event on the entire HTML document. The case is chosen according to the selection in the combo box. The "keydown" event fires whenever a keyboard key is pressed.
       
      The "mousedown" event will fire whenever the mouse key is pressed. "e" is an event object. The "altKey", "shiftKey" and "ctrlKey" properties are used to get the state of the corresponding key. "keyCode" is used to get the code of the pressed key. The numbers like 186, 222 and so on are the ASCII codes for representing a keyboard key. "which" is used to get the pressed button number like 1 for left button, 2 for middle button and 3 for the right button.

      a6p1.PNG

      a6p2.PNG

      a6p3.PNG

      a6p4.PNG

      Summary

       
      That's it; all done. Now we know how to add event listeners, how to handle the events and how to control them. We learned a bit about how event listeners evolved. We reached at the end of the article and now you can practice them and use them in whatever way you want.
       
      Live Output
       
      Don't forget to comment. :)


      Similar Articles