Chapter 9
An Eye on Events 

In This Chapter

Welcome back from intermission. (I had cookies.) Thus far, we’ve looked at several building blocks for writing JavaScript programs: operators, names, statements, and functions. The natural question, then, begs: “How do I make something useful out of all this?"

In answer to this question, I’ll first show you several interactive and reactive facilities of JavaScript (in this case, event handling). In short, that is what enables your JavaScript program to recognize and react to user actions within a Web page. First, however, allow me to finish my cookie...crunch crunch—mmm—okay. Thanks.

The Main Event

By and large, the execution of your JavaScript programs needs to be "triggered" by something. Although you may, in some cases, want code to execute immediately when the page loads, much of JavaScript's usefulness comes in its capability to be triggered.

Consider the mugs and sweaters you've been selling in program examples in the previous chapters. Most of those examples revolve around calculations you would upon receipt of a new purchase order from a Web user. Thus, receiving a new order triggers those JavaScript programs. Anything that might trigger execution of JavaScript code is known as an event.

Events are most often triggered by the user of your Web page. Common events include clicking on page elements (radio buttons, form submit buttons, URL links, and so on), entering values, and positioning the mouse pointer over certain elements. Your JavaScript program and/or programs that reside in the HTML source of the page will usually be triggered by these various events. Therefore, you need to learn what these events are, how to watch for them, and how to trigger JavaScript code in response.

Who They Are

Each event has a name by which you'll refer to it, so the logical place to begin is with a name and description of each event JavaScript is capable of recognizing. The eight events are covered in the following subsections:

Click

Focus

Blur

Change

MouseOver

MouseOut (New to JavaScript 1.1)

Select

Submit and Reset

One Eye Open: Watching for Events

For each particular page element (link, form, and so on), you specify events to watch for in the form of an attribute of the tag that defines that element. Event attributes take this form: 

onEvent="JavaScript code"

First, consider a simple example; after all, specifics make more sense than general definitions.

Recall the link tag in HTML. In typical HTML, you would define a link in the following way:

<A HREF="url to link to">Text to appear highlighted in page</A>

The user browsing your Web page sees "Text to appear highlighted in page" as a colored link. If he clicks that link, he is taken to the new page defined by the URL specified in the HREF attribute.

This is typical HTML. Now, let's add event watching to it. Suppose you want to launch a certain JavaScript program if the user moves the mouse over the link. That would require a MouseOver event trigger. Recall that you watch for an event with the attribute—in this case, you watch for onMouseOver="JavaScript code". To do so, you add the attribute into the tag that defines the link, modifying the example in this way:

<A HREF="url to link to" onMouseOver="JavaScript code">Text to
appear highlighted in page</A>
For example, you can change the message in the browser’s status bar to display the resulting action of clicking a button:
<form>
<input type=button value=”Roll Dice” onMouseOver=”window.status=’Click this
button to roll the dice and begin a new round’>
</form>

Keystone Caps

Remember that JavaScript is case-sensitive. Within JavaScript code, it matters whether you refer to a 
variable with upper- or lowercase letters. Referring to JavaScript statements with uppercase letters will 
result in errors. However, HTML code is not case-sensitive. Tags and their attributes (which includes 
onEvent attributes) can be in either upper- or lowercase. For the purposes of writing this book, though,
I use “onEvent” because it is easier to read than “onevent.” Do remember that any JavaScript code 
included between the quotation marks in the onEvent attribute is subject to JavaScript's case-sensitivity.

Between the Lines: Calling an Event Handler

Function Call

Explicit Code

Besides the elegant solution of a function call, you can write out explicit JavaScript statements within the double quotation marks. You can write an entire JavaScript program of any length, but anything more than a statement or two is probably a good candidate for a function. You should remember two notable rules if you write out JavaScript code as an event handler:

Here is an example of the same link definition, but with explicit JavaScript code as the event handler:

<A HREF="http://www.yahoo.com" onMouseOver="total=0 ; 
for (count=0;count<=10;count++) {total += 5} ;
half=total/2">Text to appear highlighted in page</A>

Now, I didn't say this example did anything useful; in this case, when the user moves the pointer over the link, the event handler is executed. It adds the value 5 to the variable total ten times in a loop, and then assigns half of total to the variable half. Perhaps at some later stage in the Web page, these variables will be used for some further calculations. In any case, the above is an example of explicit JavaScript code as an event handler.

Event Handler Rules
You cannot specify an external file as the JavaScript event handler within the onEvent attribute. However, as previously discussed, you can include external JavaScript functions at the HEAD of the Web page with the <SCRIPT src="URL of myfuncs.js"> and </SCRIPT> tags, and those functions may then be called normally as event handlers in the onEvent attribute.

 

Resetting an Event Handler in JavaScript 1.1

Both event handlers above (function calls and explicit code) were specified within HTML tags. In JavaScript 1.1, it’s also possible to set an event handler within JavaScript code.

For instance, suppose your Web page has a form button named ClickMe. You can define an event handler for ClickMe within JavaScript code as follows:

document.formname.ClickMe.onclick = function1

In the above example, ClickMe is a button within the form formname. We’ve assigned function1 to be the event handler for a Click event of ClickMe. Note that the function above is not followed by the traditional parentheses, as in function1(). When setting an event handler in JavaScript code, you leave out the parentheses; including them would cause the function to execute immediately.

Using code like that above, you can change the event handler assigned to an event, even if that event handler was previously defined in HTML tags. You’ll see a simple example of this later in the chapter. 

Examples, Exemplars, and Instantiations

At this point, you know the events, you know how to watch for them in HTML tags, and you know how to call the JavaScript event handlers. In fact, that's all you need to know. However, for the sake of clarity, let’s run through examples of event triggers for some more types of events. Although they all follow the same rules (outlined earlier), it's nice to see how a specific event is handled so you can refer to it later on.

onClick

onClick and Canceling an Event

onFocus

onSubmit

Resetting Event Handlers in JavaScript 1.1

Earlier in this chapter, you learned that in JavaScript 1.1, you can set or assign event handlers within JavaScript code. You saw that in the following example:

document.formname.ClickMe.onclick = function1

Now let’s elaborate on the above code to see how you can better take advantage of this new feature of JavaScript 1.1. Imagine, for instance, that your page contains two form elements: a button and a check box. When the user clicks the button, the onClick event calls an event handler; however, which event handler it calls depends upon whether the check box is checked or unchecked.

Consider the JavaScript 1.1 code below:

<SCRIPT>
function event1() 
{window.alert("Checkbox enabled")}
function event2() 
{window.alert("Checkbox disabled")}
function check()
{
if (document.Formica.checkbox.status == true)
{document.Formica.ClickMe.onclick = event1}
else {document.Formica.ClickMe.onclick = event2}
}
</SCRIPT>
<FORM NAME="Formica">
<INPUT TYPE="checkbox" NAME=checkbox STATUS=true onClick="check()">Checkbox Enabled<HR>
<INPUT TYPE="button" NAME=ClickMe VALUE="Click Me!">
</FORM>
<SCRIPT>check()</SCRIPT>

In the above code, you first defined three functions: event1(), event2(), and check(). Both event1() and event2() are event handlers for an onClick event of the ClickMe button. The function check() is our focal point: it determines the status of the check box and sets the appropriate event handler (either event1 or event2) to the onClick event for the ClickMe button.

In action, if the user enables the check box and then clicks the ClickMe button, a JavaScript alert window appears, stating that the check box is enabled. Conversely, if the user disables the check box and then clicks the ClickMe button, an alert window appears, stating that the check box is disabled.

Notice that you define an onClick event in the HTML tag for the check box, thus calling the check() function and properly assigning the event handler for the ClickMe button. 

Lastly, notice the final line of code in the above example: 

<SCRIPT>check()</SCRIPT>

This explicitly calls the check() function one time so that the ClickMe event handler is properly set before the user first clicks the check box.

The Least You Need to Know

Once again, reading the full chapter is an excellent idea. The following list is a fair summary, but it’s far from detailed instruction.

Previous Chapter Next Chapter


Beginning of ChapterTable of ContentsBook Home PageQue Home Page


For comments or technical support for our books and software, select Talk to Us.
To order books, call us at 800-716-0044 or 317-228-4366.

© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.