Code With Logic

Creating Code For Simplicity but Logic For Need

Working With JavaScript Events


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 by 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 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 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:

    <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 seperated 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 lead to the birth of a new way of applying event handling on elements. That way was:

Document.getElementById(“e1”).addEventListener(“click, myFunction, false);

“addEventListener” is a function to add an event listener to an element. The first parameter is a 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:

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:


It cancels the default action of the event.


It is used for enabling or disabling the event propagation.


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 partcular 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:



    <link href=”;rel=”stylesheet” type=”text/css” />

    <script src=””></script>

    <script src=””></script>

    <meta charset=”utf-8″ />

    <title>Event Handling</title>


        /* we will use this section for adding css classes */





        $(document).ready(function () {

            // We will use this for adding our jQuery





Let’s start

Now first paste this snippet into HTML:

    Select what you want to block :

    <select id=’i1′ onchange=”block();”>

  <option >Ctrl </option>

  <option >alt </option>

  <option >Ctrl+Shift </option>

  <option >F12 </option>

  <option >Right Click</option>

  <option >F5</option>

  <option >Left Click</option>   

  <option >Middle Click</option>   

  <option >Numbers</option>

  <option >Characters</option>

  <option >Special Characters</option>


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:

<div id=’dlg’>


      <div id=’msg’>Message will appear here</div>


This snippet basically creates an output window for our demo.

Now add this css for styling purpose only


  border:1px solid #1245aa;



  box-shadow:0px 0px 250px #45ab45






  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.             document.addEventListener(“keydown, altBlk);

  22.             break;

  23.         case 2:

  24.             ctrlShiftBlk = function (e) {

  25.                 if (e.ctrlKey && e.shiftKey) {

  26.                     showMsg(“Ctrl + Shift key blocked!”);

  27.                     e.preventDefault();

  28.                 }

  29.             };

  30.             document.addEventListener(“keydown, ctrlShiftBlk);

  31.             break;

  32.         case 3:

  33.             F12blk = function (e) {

  34.                 if (e.keyCode == 123) {

  35.                     showMsg(“F12 key blocked!”);

  36.                     e.preventDefault();

  37.                 }

  38.             };

  39.             document.addEventListener(“keydown, F12blk);

  40.             break;

  41.         case 4:

  42.             rtclkblk = function (e) {

  43.                 if (e.which == 3) {

  44.                     showMsg(“right click blocked!”);

  45.                     e.preventDefault();

  46.                 }

  47.             };

  48.             document.addEventListener(“mousedown, rtclkblk);

  49.             break;

  50.         case 5:

  51.             f5blk = function (e) {

  52.                 if (e.keyCode == 116) {

  53.                     showMsg(“F5 Key blocked! No more refresh :D”);

  54.                     e.preventDefault();

  55.                 }

  56.             };

  57.             document.addEventListener(“keydown, f5blk);

  58.             break;

  59.         case 6:

  60.             leftclickblk = function (e) {

  61.                 if (e.which == 1) {

  62.                     showMsg(“Left click blocked!”);

  63.                     e.preventDefault();

  64.                 }

  65.             };

  66.             document.addEventListener(“mousedown, leftclickblk);

  67.             break;

  68.         case 7:

  69.             middleclickblk = function (e) {

  70.                 if (e.which == 2) {

  71.                     showMsg(“middle click blocked!”);

  72.                     e.preventDefault();

  73.                 }

  74.             };

  75.             document.addEventListener(“mousedown, middleclickblk);

  76.             break;

  77.         case 8:

  78.             numbersblk = function (e) {

  79.                 if (e.keyCode >= 96 && e.keyCode <= 105 || e.keyCode >= 48 && e.keyCode <= 57) {

  80.                     showMsg(“Number keys blocked!”);

  81.                     e.preventDefault();

  82.                 }

  83.             };

  84.             document.addEventListener(“keydown, numbersblk);

  85.             break;

  86.         case 9:

  87.             charblk = function (e) {

  88.                 if (e.keyCode >= 65 && e.keyCode <= 90) {

  89.                     showMsg(“Character keys blocked!”);

  90.                     e.preventDefault();

  91.                 }

  92.             };

  93.             document.addEventListener(“keydown, charblk);

  94.             break;

  95.         case 10:

  96.             spcharblk = function (e) {

  97.                 if (e.keyCode >= 186 && e.keyCode <= 222) {

  98.                     showMsg(“Special Character key blocked!”);

  99.                     e.preventDefault();

  100.                 }

  101.             };

  102.             document.addEventListener(“keydown, spcharblk);

  103.             break;

  104.         default: alert(“wait);

  105.     }

  106. }

  107. function removeAllLis() {

  108.     try {

  109.         document.removeEventListener(‘keydown, altBlk);

  110.         document.removeEventListener(‘keydown, ctrlBlk);

  111.         document.removeEventListener(‘keydown, ctrlShiftBlk);

  112.         document.removeEventListener(‘keydown, F12blk);

  113.         document.removeEventListener(‘keydown, f5blk);

  114.         document.removeEventListener(‘mousedown, rtclkblk);

  115.     } catch (err) {

  116.     }

  117. }

  118. function showMsg(msg) {

  119.     $(“#msg”).text(msg);

  120.     $(‘#dlg’).dialog({

  121.         show: {

  122.             effect: “bounce”,

  123.             duration: 500

  124.         },

  125.         hide: {

  126.             effect: “blind”,

  127.             duration: 2000

  128.         }

  129.     });

  130. }

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 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 right button.






Thats’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 of 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. 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


This entry was posted on September 1, 2013 by in CodeProject, JavaScript.
%d bloggers like this: