JavaScript Events

This tutorial is part of a web programming course for people who have no programming experience.


Event driven programming in JavaScript allows you to invoke a function when a certain event occurs. An event can occur in many ways, for example when a user does something like hovering the mouse over an element, or when the page has finished loading. There are many events that we can 'hook into', which means that you can set up functions to be invoked when an event occurs. A very common event is when a button gets clicked. If you want to run some code when a button is clicked, you would first declare a function, and then write code that tells JavaScript to invoke the function when the button is clicked (you can 'hook into' the button click event).

To make use of event-driven programming in JavaScript, do the following:

  1. Define a function that you want to be invoked when a certain event occurs in your web page.
  2. Write code that 'hooks up' the function, so that it will get invoked when the event occurs.
  3. Wait until the event occurs. When it does, the browser will invoke the function for you.

Let's say you want a function to be invoked whenever this button is clicked, here's what the HTML for the button might look like:

<input type="button" id="myBtn" value="Click Here!" />

You could then define a function like so:

// define a function to be invoked when an event occurs
function doSomething(){
	console.log("doing something.....");
}

There are various ways to 'hook up' functions so that they are invoked when an events occur. The approach that we will mostly rely on is the addEventListener method. All DOM objects have this method (recall from the previous lesson that all element objects in the DOM share a common API), so you can invoke this method on any element object. In the example below, the element object happens to be a button, so when this button is clicked the browser will invoke the event handler function.

// 'hook up' the function, so that it will get invoked when the certain event occurs.
var myBtn = document.getElementById("myBtn");
myBtn.addEventListener('click', doSomething);

// This would be WRONG:
// myBtn.addEventListener('click', doSomething()); 

The addEventListener() method has two parameters. The first parameter specifies the name of the event we are 'listening' for. In the previous code sample we are waiting, or 'listening', for a 'click' event to occur on the button There are many other events that you can use (for example, 'mouseover', 'mouseout'). When you invoke addEventListener in your code, make sure to pass in this first parameter as a string (don't forget the quotes).

The second parameter is the name of the function that you want to be invoked when the event occurs. This function called an event handler function because it is used to 'handle' an event.

Take a good look at the code and you'll notice that are no parenthesis after 'doSomething' If we had included the parenthesis, the broswer would invoke the function right there on that line, which is not what we want to happen. We want the browser to invoke the function later, when the event occurs. So remember that when you hook up event handler functions, you do not usually invoke them in your code. Instead, the browser will invoke the function when the specified event occurs. You don't actually know when the the event handler function will be invoked, it may never be invoked (for example, if the user never clicks the button).

This is event-driven programming - waiting for events to occur and then running code when they do occur. The browser keeps track of all the events that occur in a page (there are many), and it will trigger (invoke) function calls for the ones that you've hooked into.

It's important to note again that you don't usually write code that invokes the event handler functions. You define/declare them, and hook them up, but the browser invokes them when the event occurs.

To give you an idea of just how many events you can hook into, here are a few references on JavaScript events:

Waiting for the Page to Load

Another very common event that JavaScript developers hook into is the page 'load' event. In many cases, you need to wait until the page completes loading before your JavaScript code can safely run. When the browser loads a web page, it starts reading it from the top down. When it reaches JavaScript code it will try to excecute it immediately. If this JavaScript code selects elements that are further down the page, and have not yet been loaded, then the program could crash.

To deal with this problem, wait until the page completes loading before executing your JavaScript code. In this case, you'll want to wait for the 'load' event to occur on the window object.

// define the event handler function
function setUp(){
	console.log("The page has loaded, it's safe to run your JavaScript code now");
	// ALL OF YOUR JAVASCRIPT CODE CAN GO HERE IN THE SETUP FUNCTION
}

// hook it up so that it's invoked when the window finishes loading
window.addEventListener("load", setUp);

Now you can put ALL of your JavaScript code inside the setUp function and be assured that it will not execute until the page has completed loading.

Annonymous Functions

In the previous examples, when invoking the addEventListener() method, we used the name of a function as the second parameter (and we were careful not to include the parenthesis after the name). But it's actually very common to use an annonymous function when hooking up events. Instead of declaring a function first and then hooking it up as an event handler, you can actually do both at the same time like this:

window.addEventListener("load", function(){
	// Put ALL of your JS code inside this function
});

The function that is being used as the second parameter to addEventListner() has no name, which makes it an 'annonymous' function. It usually takes a bit for beginning students to wrap their heads around this approach, but it's so commonly used that I must tell you about it. As you know by now, functions can have lots of code in them, so when I use this approach I like to do what I call 'setting the table', like this:

window.addEventListener("load", function(){});

Here you can see a little more clearly that the second parameter is a function (an annonymous one), and you can also clearly see the curly braces that will contain the body of the function. Just after the closing curly brace is the closing parenthesis for the addEventListener method call. Once I've type all this in, I put my cursor in between the curly braces, press ENTER, and then I'm ready to type the code for the body of the event handler function. In other words, I have set the table before writing the code that I actually want to execute when an event occurs. I like to set the table so that I don't forget to type the closing curly brace and paranthesis later.

When you are using a SCRIPT element to link to an external .js file, you can use the DEFER attribute to wait until the page loads to run the code in the .js file. In that case, you don't need to add an event listener for the page load event in the .js file.

Assigning an Event Handler to the Property of an Element Object

There are a few different ways that you can write code to set up event handler functions. I believe that using addEventListener() is the best approach. But you should be aware of other approaches, because you'll see them when looking at other peoples' code.

Instead of using the addEventListner() method of a DOM element object, you can also set an event handler by assigning a function to a specific property of an element object:

var myDiv = document.getElementById("myDiv");
myDiv.x = doSomething;

This JavaScript code assumes that there is a DIV element in the HTML code that looks something like this:

<div id="myDiv">Click Here!</div>

Element objects have certain proerties, whose names begin with 'on', and they represent events that can occur on the element. You can assign functions to these properties, that will be invoked (by the browser) when the event occurs on the element. It's important to note that when you use this approach, the property name begins with 'on', but when using addEventListener() don't use 'on' when passing in the first parameter. I've seen this trip up many students, but I try stick with using addEventListener to avoid the confusion. I'd also like to point out that click events aren't just for buttons. You can hook up event handlers to listen for click events on any element that appears in a web page.

In the previous example we used a function named 'doSomething'. Here's another way to acheive the same effect, this time by using an anonymous function:

myDiv.x = function(){
	alert("blah!!!");
};

Assigning an Event Handler to the Attribute of an Element

Finally, you can specify event handlers by setting certain attributes of an element in your HTML code.

<div id="myOtherDiv" x="console.log('hello');" x="console.log('bye!');">Hover Over Me!</div>

You could actually put entire JavaScript programs inside an attribute like this, but things would get really messy. You have to be very careful with how you make use of quotation marks (notice that I was careful to use single quotes for the JavaSrcipt code becuase double quotes are used to enclose the attribute value). This approach was once considered out-dated, but in recent years it has started to pop up in some modern JavaScript frameworks.

I do however want to point out something to help you connect the dots. Recall from the DOM lesson when I mentioned, "Attributes of HTML elements become properties of element objects in the DOM". In this last example we made use of the x attribute for an element in the HTML code, but in the previous example we worked with the x property and an element object that was selected from the DOM.

NEXT LESSON: Exploring the DOM API