16 - Event Handlers in Javascript

A function or a method is a piece of code to which arguments can be passed and the piece of code will be executed whenever the function is called by its name. A function can be written as a response to some kind of event. An event can be described as the occurrence of an action from the user or the browser. Functions can be written to execute when these events occur and they are called event handlers. With normal functions, we have to write the code to invoke or call the functions. Here the event handlers would be invoked by Javascript as it will keep watching and listening for the events to occur. There are different kinds of events and corresponding event handlers can be written.

Where to place event handlers

As said earlier, event handlers are also functions. Hence they can be written as we write normal kind of functions. But, there is a difference here in how these event handling functions are invoked. There are two ways to tag an event handler to a particular event. The first method involves adding an event while the second involves stating against the particular control as attribute and value. Not to worry. It is simple enough. When we dive into the different kind of events and learn to write event handlers for the same we can clear the air of lingering doubts.

Page events

A page here refers to the web page. A web page is loaded and will be ready. Then when the user requests for another page the current page is unloaded. The page can also be resized and scrolled. For each of these actions there is a corresponding event.

Event

Purpose

load

This event fires when the page loads. One can include script that needs to be executed when the page loads.

resize

This event fires when the page resizes.

scroll

This event fires when the page is scrolled

unload

This event fires when the page unloads

 

Here is an example that illustrates how the load event can be listened to.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
          function loadPage()
           {
            alert("This page has just been loaded.");
           }
         </script>
    </head>     
    <body style = "font-size:16px;" onload = "loadPage()">
     <hr>
    </body>
</html>

 

This example illustrates that the alert was invoked from the function when the page was loading.

Forms

Nowadays one mostly comes across websites that have forms in varying sizes. Feedback forms, registration forms, address forms, login forms, queries and a lot more can be found on the internet. A form is a group of controls through which user can share information and interact with the website. There are different kinds of controls like radio buttons, buttons, text boxes, check boxes, dropdown lists and so on.

There are different kinds of actions that can be performed on a form. A button can be clicked. A text box can be written on. A radio button can be selected to make a choice among others. So whenever the user interacts with a control events arise. One can write event handlers to capture these events and perform events against them.

Apart from the events triggered by the form controls one can also write event handlers for events that occur on mouse and keyboard based events. For example we can highlight a button when the mouse hovers on it. We can scroll the screen down when the space key is hit.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
          function buttonClick()
          {
            alert("A button has been clicked");
          }
        </script>
    </head>    
    <body style = "font-size:16px;">
       <hr>
        <div align="center">
          <form action = "#">
                <button onclick="buttonClick()">
                Click here
            </button>
          </form>
        </div>
        <script type="text/javascript">        
        </script>
    </body>
</html>

 

Here are some of the common events that are said to occur in HTML forms. Just like how we have done for Onclick, we would be required to do for these events too.

Event

Time of occurrence

onkeydown

This event occurs when a key on the keyboard has been pushed.

onmouseover

This event occurs when the mouse is brought over the element.

onmouseout

This event occurs when the mouse is taken away from the element.

Writing events is very important when creating websites, particularly those that are having heavy interactions with the users. They need to properly listen to what is happening and then act accordingly.

There is a method of assigning event handlers other than by specifying them as attributes.

object.addEventListener(event, event handling function, capture or bubble)
object.removeEventListener(event, event handling function, capture or bubble)

In HTML each HTML element can be assigned an attribute called ID. This would identify the element uniquely. We could attach event handlers using the element id. In event handling there is a concept known as event bubbling. One event would give rise to a series of events.

The above lines of code are used to attach event handlers to the elements by their ids. The first attribute specifies the event for which the event handler is to be invoked. The second attribute specifies which function would be handling the event. The name of the function is specified without the parenthesis. The third attribute is used to specify whether the event handler should work only when the event is captured or when the event is bubbled.

Let us use the same example as the button click above but have the code alone modified here to work according to this method.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
        function buttonClick()
        {
            alert("A button has been clicked");
        }
        </script>
    </head>
     
    <body style = "font-size:16px;">
      <hr>
        <div align="center">
          <form action = "#">
            <button id = "clicker">
                Click here
            </button>
          </form>
        </div>
        <script type="text/javascript">
          document.getElementById("clicker").addEventListener("click",buttonClick,true);
        </script>
   </body>
</html>

Like us on Facebook