Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Working With JavaScript Events

0.00/5 (No votes)
2 Oct 2013CPOL6 min read 9.3K  
How to add event listeners, how to handle the events, and how to control them.

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

<html>
<body onclick="dosomework()">
    <div onclick="dosomework()"></div>
</body>
</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:

e.preventDefault()

It cancels the default action of the event.

e.cancelBubble=true/false

It is used for enabling or disabling the event propagation.

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:

<html>
<head>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.min.css&#8221;rel="stylesheet" type="text/css" />
    <script src="></"http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
    <meta charset="utf-8″ />
    <title>Event Handling</title>
      <style>
        /* we will use this section for adding css classes */
    </style>
 </head>
<body>
      <script>
        $(document).ready(function () {
            // We will use this for adding our jQuery
        });
    </script>
</body>
</html>

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

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

This snippet basically creates an output window for our demo.

Now add this CSS for styling purpose only

#dlg{
  border:1px solid #1245aa;
  width:auto;
  height:auto;
  box-shadow:0px 0px 250px #45ab45; 
  display:none;
}
#msg{
   width:auto;
  height:auto;
  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:

function block() {
    var keyblock = document.getElementById(‘i1′).selectedIndex;
    removeAllLis();
    switch (keyblock) {
        case 0:
            ctrlBlk = function (e) {
                if (e.ctrlKey) {
                    showMsg("Control key blocked!");
                    e.preventDefault();
                }
            };
            document.addEventListener("keydown", ctrlBlk);
            break;
        case 1:
            altBlk = function (e) {
                if (e.altKey) {
                    showMsg("Alt key blocked!");
                    e.preventDefault();
                }
            };
        document.addEventListener("keydown", altBlk);
            break;
        case 2:
            ctrlShiftBlk = function (e) {
                if (e.ctrlKey && e.shiftKey) {
                    showMsg("Ctrl + Shift key blocked!");
                    e.preventDefault();
                }
            };
            document.addEventListener("keydown", ctrlShiftBlk);
            break;
        case 3:
            F12blk = function (e) {
                if (e.keyCode == 123) {
                    showMsg("F12 key blocked!");
                    e.preventDefault();
                }
            };
            document.addEventListener("keydown", F12blk);
            break;
        case 4:
            rtclkblk = function (e) {
                if (e.which == 3) {
                    showMsg("right click blocked!");
                    e.preventDefault();
                }
            };
            document.addEventListener("mousedown", rtclkblk);
            break;
        case 5:
            f5blk = function (e) {
                if (e.keyCode == 116) {
                    showMsg("F5 Key blocked! No more refresh");
                    e.preventDefault();
                }
            };
            document.addEventListener("keydown", f5blk);
            break;
        case 6:
            leftclickblk = function (e) {
                if (e.which == 1) {
                    showMsg("Left click blocked!");
                    e.preventDefault();
                }
            };
            document.addEventListener("mousedown", leftclickblk);
            break;
        case 7:
            middleclickblk = function (e) {
                if (e.which == 2) {
                    showMsg("middle click blocked!");
                    e.preventDefault();
                }
            };
            document.addEventListener("mousedown", middleclickblk);
            break;
        case 8:
            numbersblk = function (e) {
                if (e.keyCode >= 96 && e.keyCode <= 105 || e.keyCode >= 48 && e.keyCode <= 57) {
                    showMsg("Number keys blocked!");
                    e.preventDefault();
                }
            };
            document.addEventListener("keydown", numbersblk);
            break;
        case 9:
            charblk = function (e) {
                if (e.keyCode >= 65 && e.keyCode <= 90) {
                    showMsg("Character keys blocked!");
                    e.preventDefault();
                }
            };
            document.addEventListener("keydown", charblk);
            break;
        case 10:
            spcharblk = function (e) {
                if (e.keyCode >= 186 && e.keyCode <= 222) {
                    showMsg("Special Character key blocked!");
                    e.preventDefault();
                }
            };
            document.addEventListener("keydown", spcharblk);
            break;
        default: alert("wait");
    }
}

function removeAllLis() {
    try {
        document.removeEventListener(‘keydown‘, altBlk);
        document.removeEventListener(‘keydown‘, ctrlBlk);
        document.removeEventListener(‘keydown‘, ctrlShiftBlk);
        document.removeEventListener(‘keydown‘, F12blk);
        document.removeEventListener(‘keydown‘, f5blk);
        document.removeEventListener(‘mousedown‘, rtclkblk);
    } catch (err) {
    }
}
function showMsg(msg) {
    $("#msg").text(msg);
    $(‘#dlg’).dialog({
        show: {
            effect: "bounce",
            duration: 500
        },
        hide: {
            effect: "blind",
            duration: 2000
        }
    });
}

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.

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

Don’t forget to comment. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)