O'Reilly logo

JavaScript Cookbook by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 7. Handling Events

7.0. Introduction

Events, especially within an interactive environment such as a browser, are what make JavaScript essential. There is very little JavaScript functionality that isn’t triggered by some event, even if the only event that occurs is a web page being loaded. Event handling in JavaScript depends on determining which event or events you want to trigger some activity, and then attaching JavaScript functionality to the event.

The earliest form of event handling is still one of the most common: the use of an event handler. An event handler is an element property that you can assign a function, such as the following, which assigns a function to the window.onload event handler:


You can also assign an event handler directly in an element, such as in the opening body tag:

<body onload="someFunction()">

However, I don’t recommend embedding events directly in page elements, as it makes it difficult to find and change the event handling routines later. If you use the first approach, which is to assign a function to an event handler in script element or in a JavaScript library, you only have to look in one place in order to make changes.


JavaScript lives in an enormous number of environments, as Chapter 21 demonstrates. Most of this chapter is focused on JavaScript within a browser or browser-like environment.

Some Common Events

There are several events that can be captured via JavaScript, though not all are available to all web page elements. The load and unload events are typically used with the window object to signal when the page is finished loading, and just before the page is unloaded because the web page reader is navigating away from the page. The submit and reset events are used with forms to signal when the form is submitted, or has been reset by the reader.

The blur and focus events are frequently used with form elements, to determine when an element gets focus, and loses it. Changing a form value can trigger the change event. The blur and change events are especially handy if you need to validate the form values.

Most web page elements can receive the click or dblclick event. Other mouse events include mousedown, mousemove, mouseout, mouseover, and mouseup, which can be used to track the cursor and mouse activity.

You can also track keyboard activity with events such as keydown and keyup, as well as keypress. If something can be scrolled, you can typically capture a scroll event.

Event History and New Event Handling

There’s a history to event handling with JavaScript. The earliest form of event handling is frequently termed “DOM Level 0” event handling, even though there is no DOM Level 0. It involves assigning a function directly to an event handler.

You can assign the event handler in the element directly:

<div onclick="clickFunction()">

or assign a function to the event handler in a script element or JavaScript library:


In the last several years, a newer DOM Level 2 event handling system has emerged and achieved widespread use. With DOM Level 2 event handling, you don’t assign a function to an event handler directly; instead, you add the function as an event listener:


The general syntax is:


The last parameter in the function call has to do with how events are handled in a stack of nested elements. For example, if you’re capturing an event for a link within a div element, and you want both elements to do some processing based on the event, when you assign the event listener to the link, set the last parameter to false, so the event bubbles up to the div element.

You can also remove event listeners, as well as cancel the events themselves. You can also prevent the event from propagating if the element receiving the event is nested in another element. Canceling an event is helpful when dealing with form validation, and preventing event propagation is helpful when processing click events.

It’s up to you to decide which level of event handling meets your needs. If you’re doing simple event handling—not using any external JavaScript libraries and not worried about canceling events, or whether events bubble up in a stack of elements—you can use DOM Level 0 events. Most of the examples in this book use window.onload to trigger the demonstration JavaScript.

If you need the more sophisticated event handling, including the ability to more easily control events, you’ll want to use DOM Level 2 events. They can be easily encapsulated into a JavaScript library, and can be safely integrated into a multi-JavaScript library environment. However, the fly in this little event handling pie is that the DOM Level 2 event handling isn’t supported universally by all browsers: Microsoft has not implemented DOM Level 2 event handling with IE8 or earlier. However, it’s fairly simple to work around the cross-browser issues, as detailed in Recipe 7.3.


There’s ongoing work to create a new DOM Level 3 event handling, which builds on the work of the DOM Level 2 event handling and is included as part of the Web Applications work at the W3C. However, implementation of the newer material is sparse, at best.

New Events, New Uses

There are newer events to go with the newer models, and to go with a nonbrowser-specific DOM. As examples of DOM events, the DOMNodeInserted and DOMNodeRemoved events are triggered when a node is added or removed from the page’s document tree. However, I don’t recommend using the W3C event for general web pages, as these events are not supported in the current versions of IE, and only partially supported in most other browsers. Most web application authors wouldn’t need these events, anyway.

There are also events associated with the increasingly popular mobile and other hand-held computing environments. For instance, Firefox has a nonstandard set of events having to do with touch swiping, which Mozilla calls the mouse gesture events. It’s interesting, but use with caution until there’s wider acceptance of the newer events. We’ll take a look at one type of mobile device event handling towards the end of the chapter.

See Also

See Recipe 7.3 for a demonstration of handling cross-browser event handling.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required