Events in JavaScript
- Techniques to Handle Events
- The First Event: load
- The Event Object
- The Secret Life of Events
- Striped Table with Rollovers
- The Up and Down Life of Keys
- Summary
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.
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
var clickableImage=document.getElementById("dog_pic"); clickableImage.onclick=showLargeImage;
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.
function showLargeImage() { thePic=document.getElementById("dog_pic"); // do something with the pic }
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
Introduced with the W3C DOM model, event listeners provide comprehensive event registration.
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);
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.
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.