Categories
JavaScript Tutorials

Handling events

When JavaScript does something in response to these events, it’s called event handling. Over the years, browser makers have implemented several ways for JavaScript programs to handle events. As a result, the landscape of JavaScript events has been one of incompatibilities between browsers.

Today, JavaScript is getting to the point where the old, inefficient techniques for handling events can soon be discarded. However, because these older techniques are still widely used, it’s important that they are covered here.

Using inline event handlers

The first system for handling events was introduced along with the first versions of JavaScript. It relies on special event attributes like “onclick”. The inline event listener attributes are formed by adding the prefix “on” to an event(For example, to handle the “click” event, we need the “onclick” event listener attribute). To use them, add the event attribute to an HTML element. When the specified event occurs, the JavaScript within the value of the attribute will be performed.

Note: Remember that “click” is an event and “onclick” is the corresponding event listener.

For example, Listing 11-1 pops up an alert when the link is clicked.

Listing 11-1: Attaching an onclick Event Handler to a Link Using Inline Method:

<a href="home.html" onclick="alert('Go Home!');">Click Here To Go Home</a>

If you put this markup into an HTML document and click the link, you see an alert window with the words ‘Go Home!’ When you dismiss the alert window,the link proceeds with the default event handler associated with the a element — namely, following the link in the href attribute.

In many cases, you may not want the default action associated with an element to happen. 

For example, what if you just wanted the alert window in Listing 11-1 to pop up without doing anything else?

JavaScript programmers have come up with several different methods to prevent default actions. One technique is to make the default action be something that is inconsequential.

 For example, by changing the value of the href attribute to a #, the link will point to itself:

<a href="#" onclick="alert('Go Home!');">Click Here</a>

A better method, however, is to tell the event handler to return a boolean false value, which tells the default action not to run:

<a href="homepage.html" onclick="alert('Go Home!'); return false;">Click Here</a>

Event handling using element properties

One of the biggest problems with the older, inline technique of assigning events to elements is that it violates one of the best practices of programming:

keeping presentation (how something looks) separate from functionality (what it does). 

Mixing up your event handlers and HTML tags makes your web pages more difficult to maintain, debug, and understand. With version 3 of their browser, Netscape introduced a new event model that allows programmers to attach events to elements as properties. Listing 11-2 shows an example of how this model works.

Listing 11-2: Attaching Events to Elements Using Event Properties:

<html> 
  <head>
    <title>Counting App</title>
    <script>
      // wait until the window is loaded before registering the onclick event
      window.onload = initializer;
      // create a global counting variable
      var theCount = 0;
      /** Registers onclick event */
      function initializer(){
        document.getElementById("incrementButton").onclick = increaseCount;
      }
      /**Increments theCount and displays result.*/
      function increaseCount(){
        theCount++;
        document.getElementById("currentCount").innerHTML = theCount;
      }
    </script>
  </head>
  <body>
    <h1>Click the button to count.</h1>
    <p>Current Number: <span id="currentCount">0</span></p>
    <button id="incrementButton">Increase Count</button>
  </body>
</html>

Click the button to count.

Current Number: 0

Increase Count

One thing to notice about Listing 11-2 is that function names that are assigned to the event handler don’t have parentheses after them. What’s going on here is that the whole function is assigned to the event handler and is telling it “run this when this event happens” rather than actually using a function call. If you add the parentheses after the function name, the function will be executed, and its result will be assigned to the onclick handler, which is not what we want.

Event handling using addEventListener

Although the previous two methods of event handling are very commonly used and are supported by every browser, a more modern and flexible way to handle events (and the recommended way for new browsers) is to use the addEventListener() method. The addEventListener() method helps us to attach event handlers on elements. It listens to events and handles it according to the attached event handler.

The basic syntax for addEventListener is as follows:

target.addEventListener(eventType, eventHandler)

Here, eventType is the type of event(such as click) to be passed as a string and eventHandler is the function definition or function name to be performed.

There are different ways to use the addEventListener method. Let’s see them one by one.

Using function definition

button.addEventListener('click', function(){ console.log("hi") });

Here, we are binding the click event on the button to a function that prints “hi” in the console. In the above syntax, the target is the button and the eventType is click which is passed as a string to the addEventListener method. The function definition is the second argument for the addEventListener method which prints “hi” in the console whenever the click event on the button is triggered.

Using function name

button.addEventListener("click", printHi);

function printHi(){
  console.log("hi");
}

This is another way of using the addEventListener method. Here, instead of the function definition, we are using the function name which is declared just below the addEventListener statement. This makes the code look clean. If we have a function with more execution lines, the addEventListener method would look clumsy if we define the function inside the addEventListener method.

Attaching multiple handlers

button.addEventListener("click", printHi);
button.addEventListener("click", printHello);

function printHi(){
  console.log("hi");
}

function printHello(){
  console.log("hello");
}

We can even attach more than one handler to the same target. All the handlers will work properly without overriding each other. Here, we are attaching two different handlers to the same click event on the same target. So, both the handlers will work in sequence i.e. first the “hi” will printed and then the “hello” will be printed.

Examples

Print “Hello World” in the console by attaching an inline event handler to a button.

<html>
  <head> </head>
  <body>
    <button onclick="print()">Print</button>
    <script>
      function print(){
        console.log('Hello World');
      }
    </script>
  </body>
</html>

Print the sum of two numbers by attaching event handler to element properties of a button.

<html>
  <head> </head>
  <body>
    <button id="btn">Add 2 and 3</button>
    <script>
      document.getElementById('btn').onclick = sum;
      function sum() {
        var x = 2 + 3;
        console.log(x);
      }
    </script>
  </body>
</html>