This chapter is from the book

This chapter is from the book

In a modern web site or browser-based application, JavaScript’s primary purpose is to provide responses to the user interactions with the interface, or to be more technically precise, to handle events that are triggered by user actions.

Events are messages that the browser fires off in a constant stream as the user works; for example, every time the user moves the pointer over an HTML element, clicks the mouse, or moves the cursor into a field of a form, a corresponding event message is fired. JavaScript receives these messages, but does nothing unless you provide an event handler that provides a response to them.

Your ability to write code that can monitor and respond to the events that matter to your application is key to creating interactive interfaces.

To make your application respond to user action, you need to:

Decide which events should be monitored

Set up event handlers that trigger functions when events occur

Write the functions that provide the appropriate responses to the events

You’ll see the details of this process throughout this chapter. For now, just get the idea that an event, such as click, is issued as the result of some specific activity—usually user activity, but sometimes browser activity such as a page load—and that you can handle that event with an event handler. The event handler is always the name of the event preceded by “on”; for example, the event click is handled by the onclick event handler. The event handler causes a function to run, and the function provides the response to the event. Table 4.1 lists the most commonly used event handlers.

Table 4.1. This table contains a list of the most commonly used event handlers.

Event Category

Event Triggered When...

Event Handler

Browser events

Page completes loading

onload

Page is removed from browser window

onunload

JavaScript throws an error

onerror

Mouse events

User clicks over an element

onclick

User double-clicks over an element

ondblclick

The mouse button is pressed down over an element

onmousedown

The mouse button is released over an element

onmouseup

The mouse pointer moves onto an element

onmouseover

The mouse pointer leaves an element

onmouseout

Keyboard events

A key is pressed

onkeydown

A key is released

onkeyup

A key is pressed and released

onkeypress

Form events

The element receives focus from pointer or by tabbing navigation

onfocus

The element loses focus

onblur

User selects type in text or text area field

onselect

User submits a form

onsubmit

User resets a form

onreset

Field loses focus and content has changed since receiving focus

onchange

Techniques to Handle Events

In this section, I’ll show you four techniques that you can use to trigger JavaScript functions in response to events. The first two require adding JavaScript into the markup, so I try to avoid them, preferring techniques where event handlers are programmatically added to and removed from elements as needed. In small projects, such as simple Web sites, the first two techniques work just fine, but with important caveats that I will discuss for each one.

JavaScript Pseudo Protocol

If you worked with JavaScript in years past, you may have used the the JavaScript pseudo protocol to trigger a function from a link:

<a href="javascript:someFunctionName();">Link Name</a>

When the user clicks the link, the function someFunctionName is called. No onclick is stated; this technique simply replaces the href value. The problem with this approach is that it completely replaces the URL that normally would be the href value. If the user doesn’t have JavaScript running or the associated JavaScript function fails to load for some reason, the link is completely broken. This approach also adds JavaScript into the markup, an issue I’ll discuss after I show you the second method. In short, avoid triggering events with the pseudo protocol.

Inline Event Handler

An inline event handler, as you saw briefly in Chapter 2, attaches an event handler directly to an element.

<input type="text" onblur="doValidate()" />

Here, a form text field has the JavaScript function doValidate associated with its blur event—the function will be called when the user moves the cursor out of the field by pressing Tab or clicks elsewhere. The function could then check if the user actually typed something in the field or not.

Focus and Blur

When the user clicks into a text field, the focus event message is fired because the focus of the keyboard is now on that field, and anything the user types then appears in that field. If the user then presses Tab or clicks elsewhere to move the cursor out of that field, the field loses focus and the blur message is fired.

Inline event handlers have been the standard way of triggering events for years, so if you have to work on a Web site that has been around for a while, you will no doubt see inline handlers all over the markup. A benefit of inline handlers is that the this keyword is bound to the function that is called from an inline handler. To illustrate this point, here’s a link that calls a function named addClass

<a href="somePage.html onClick="addClass()">

so in the function you can simply write

this.className="hilite";

without having to first “get” the element.

Additionally, you don’t have to worry about users triggering JavaScript events that act on the DOM before the DOM has loaded into the browser, because the event handler is attached to the markup. We’ll examine this DOM ready issue in “The First Event: load” section of this chapter.

However, both benefits can be realized using the two other ways of associating events with elements. Before I describe them, keep in mind that neither of the first two techniques is ideal in that they mix JavaScript with the HTML. In the previous example, the addClass function is permanently associated with this HTML element. If you change the function’s name or remove it from your code, you’ll also have to find and remove every occurrence of the handler in the markup. Also, if for some reason the addClass script doesn’t load, JavaScript will throw an error when the link is clicked. In a modern Web application—in the interests of accessibility, maintainability, and reliability—you want to keep JavaScript and CSS out of your HTML markup.

Because inline handlers are still widely used, it would be remiss of me not to show you how they work in some detail, because they will be around for years to come. In later chapters, I’ll show you examples of inline handlers and how to use them. That said, I hope they will be fading into obscurity as programmers become more aware of Web standards and the advantages of using JavaScript to register events with their associated elements. With all this in mind, let me now show you the ways you can create responses to events without adding JavaScript into the HTML markup.

Handler as Object Property

This example shows a two-step process. First, I assign an object—an HTML element with the ID dog_pic—to a variable. In line 1 of the example, the object representing the HTML element is stored in the clickableImage variable. Second, I assign the event handler onclick as a property of the object, using a function name as the onclick property’s value. The function showLargeImage will now run when the user clicks on the element with the ID dog_pic.

While this technique has the desirable quality of keeping the JavaScript out of the markup, it has a couple of serious drawbacks.

First, only one event at a time can be assigned using this technique, because only one value can exist for a property at any given time. I can’t assign another event to the onclick property without overwriting this one, and for the same reason, another event that was previously assigned is overridden by this one.

Second, when the user clicks on this element and the function is called, that function has to be hard-coded with the name of the object so that it knows which element to work on.

If you change the object that is the source of the event, you will also have to modify the function.

For this reason, the “handler as object property” technique is suitable only when you just want to assign one event to one object, such as running an initial onload function once the page is first loaded (see “The First Event: load” section later in this chapter). However, for the reasons noted, it really doesn’t provide a robust solution for use throughout an RIA, where events commonly get assigned and removed from objects as the application runs. In almost every case, the best way to manage events is to use event listeners.

Event Listeners

An event listener does what its name suggests: After being attached to an object, it then listens patiently for its event to occur. When it “hears” its event, it then calls its associated function in the same way as the “handlers as object properties” method but with two important distinctions.

First, an event listener passes an event object containing information about its triggering event to the function it calls. (I emphasize this point because it is so important.) Within the function, you can read this object’s properties to determine the target element, the type of event that occurred—such as click, focus, mousedown—and other useful details about the event.

This capability can reduce coding considerably, because you can write very flexible functions for key tasks, such as handling clicks, that provide variations in their response depending on the calling object and triggering event. Otherwise, you would have to write a separate, and probably very similar, function for every type of event you have to handle. You will learn how to write functions with this kind of flexibility later in the chapter.

Second, you can attach multiple event listeners to an object. As a result, you don’t have to worry when adding one listener that you are overwriting another that was added earlier, as you do when simply assigning an event as an object property.

While both the W3C and Microsoft browsers enable event handlers, they differ in the way those handlers are attached to elements and in the way they provide access to the event object. I’ll start with the W3C approach, which will be the de facto standard in the future, and then discuss how event listeners work in Microsoft browsers.

W3C Event Model

Here’s the W3C technique for adding listeners to elements. I’ll add two listeners to a form’s text field that will cause functions to run when the user clicks (or tabs) into or out of the field:

Now the function doHighlight will be called when the cursor moves into the field, and the function doValidate will be called when the cursor moves out of the field. (The third argument, false, relates to event bubbling, a concept that can wait until later in this chapter.) I can attach as many event listeners as I want to the object in this manner.

I can remove the events from the element in a similar way using the removeEventListener method.

The Microsoft Event Model

Microsoft’s event registration model is slightly different. The equivalent of this W3C style

emailField.addEventListener('focus',doHighlight,false);

in the Microsoft model is

emailField.attachEvent('onfocus',doHighlight);

and the equivalent of this W3C style

emailField.removeEventListener('focus',doHighlight,false);

in the Microsoft model is

emailField.detachEvent('onfocus',doHighlight);

You only need to explicity remove event handlers if your application requires that an element no longer respond to an assigned event. In most cases, you only add event listeners and don’t explicity remove them. They only persist for as long as the page is loaded in the browser.

Note the use of on, as in onfocus, in the name of the event for the Microsoft version. Clearly, there are some syntax variations here, so let’s look at how to write code that works on both browsers.

An Addevent Helper Function

To add event listeners to elements correctly, regardless of the user’s browser type, I’ll use an existing helper function written by John Resig that can determine the correct event models to use. This function accepts the following arguments:

The element to which the listener should be attached

The type of event to listen for

The name of the function to call when the event occurs

It will then use these arguments to construct a correctly formatted event listener registration for the user’s browser.

The function first tests if the browser supports Microsoft’s attachEvent method (highlighted) and then branches the code accordingly.

Removing events can be achieved with a second, similar helper function.

These functions, as you can see, are somewhat complex, but fortunately you don’t have to understand them; you just have to be able to use them. If you wanted to add an event listener to the email field from the preceding example, all you would have to do is call the addEvent helper function like this:

addEvent(emailField, 'focus', doHighlight);

The three arguments are the element, the event, and the function to call when that element receives that event. The function then takes care of formatting the event registration appropriately for the browser on which it is running.

Software Design Patterns

If you are a designer, you may be aware of the classification of common user interface interactions into design patterns—such as Wizard, multiple undo, and drag-and-drop to name just a few—that define each interaction’s appropriate use and implementation. Design patterns document successful user interactions, give designers a common vocabulary, and most of all, provide users with familiar interactions across the sites they visit. Jenifer Tidwell’s Designing Interfaces (O’Reilly, 2005) is the seminal work on this subject and essential reading for all interface designers.

A similar set of design patterns exists in software also and provides a standardized way to solve and discuss common programming problems. The first major classification of software design patterns was published in Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1994) by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (known as “The Gang of Four”).

Most of the helper functions used in Scriptin’ with JavaScript are simple implementations of the Façade pattern, where “a common interface is provided to two or more interfaces in a subsystem.” The code addresses a single interface—in the case of adding event listeners, the addEvent function—and the interface takes care of addressing, in a syntactically correct manner, one of two objects—addEventListener or attachEvent—depending on the user’s browser. By using these Façade pattern helpers, you abstract away cross-browser issues and simply pass your requests to these intermediate objects that resolve them for you.

As your skills grow, studying design patterns can help you write better code, because you’re then using best coding practices and can avoid struggling to discover solutions to coding problems that were discovered and proven long ago.

Event listener registration is yet another example of the cross-browser issues you face with JavaScript. However, once you have a nice little collection of helpers or a framework such as jQuery, you don’t have to worry about them as much.

A common time at which to add listeners to elements is when the page first loads, or to be more specific, upon an event that virtually every JavaScript application must detect and handle—the load event that is triggered when the page is fully loaded and rendered in the browser.