Chapter 10
An Eye on Events
In This Chapter
Welcome back from intermission. (I had cookies.) Some might think it odd to progress four chapters into JavaScript programming, and have yet to even mention HTML in this part of the book. After all, JavaScript is all about Web programming, and HTML is the standard fashion for Web pages. You might think to yourself at this point, "Great, now I understand the building blocks of JavaScript, can write functions and loops, and can create objects-but how do I make something useful out of all this?"
In answering this question, you'll look at the first of several Web-page specific facilities of JavaScript; in this case, event handling. In short, that is the capability for your JavaScript program to recognize and react to user actions within a web page. Let me just finish this last cookie I sneaked in from the rec hall.
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 upon loading the page, 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 make upon receiving a new purchase order from a Web user. Thus, receiving a new order would be a trigger to 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.
Each event has a name by which you'll refer to it, so the logical place to begin is a name and description of each event which JavaScript is capable of recognizing. The events are as follows:
The Click event occurs when a user clicks the mouse button on either a link or a form element. Form elements include buttons, check boxes, and "reset" or "submit" buttons.
The Focus event occurs when a user clicks the mouse or uses the Tab key to bring attention to a given form element. That is, when a user clicks on a form element to activate it, preparing it to accept entry, a Focus event has occurred. Note that this is different from when the user enters data into the element-focus merely occurs when the element is activated for entry. Some use the Tab key to move between form elements; this, too, triggers a Focus event as each element becomes active.
The Blur event is the opposite of the Focus event; it occurs when a user removes the focus from a currently in-focus form element, either by clicking or tabbing to another form element (thus moving the focus to a new element), or by clicking on some inactive region of the page, thus removing focus from any element.
The Change event occurs after a user modifies the input into a form element, such as a text input area. It also occurs if a selection is made from a selection box (the form element that allows a user to make a selection from a scrolling list of choices). Note that the Change event occurs only after a modified entry loses focus. That is, the moment a user begins entering data into a form element, the Change event is not triggered. It is triggered when they're done, indicated when they remove focus from the element, such as by clicking elsewhere.
The MouseOver event occurs when the mouse pointer is moved over a link. You may have noticed, while using the Web, that when you move the pointer over a link within a page, the URL address of that link appears in a status line. That is an example of a MouseOver event having occurred.
A Select event occurs when a user selects text (dragging the mouse across an area of text while holding down the left button, highlighting it) within a form's text entry element.
A user might do this just before modifying the text in the entry.
A Submit event occurs when a user clicks the "Submit" button of a form element. Note that this event occurs before the form is actually submitted (as defined in the <FORM> tag). This allows you to trigger JavaScript code that might perform some analysis or evaluation, and as a result allow or prevent the form from actually being submitted.
The preceding are the basic events that may occur in a Web page as a result of user interaction. From these events, you will choose which are relevant to watch for within your particular page, and what JavaScript code to trigger as a result.
You specify events to watch for, in the case of each particular page element (link, form, and so on), in the form of an attribute of the tag that defines that element. Event attributes take the form onEvent="JavaScript code". Let's consider a simple example; specifics make more sense than general definitions.
Recall the link tag in HTML. In typical HTML, you would define a link 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 on that link, he is taken to the new page defined by the URL specified in the HREF attribute above.
| Keystone Caps |
| Remember that JavaScript is case-sensitive. It matters, within JavaScript code, 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 can be in either upper- or lowercase, which includes onEvent attributes. However, for the purposes of book writing, onEvent is easier to read than onevent. Do remember that any JavaScript code included in the onEvent attribute between the quotation marks is subject to JavaScript's case-sensitivity. |
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, onMouseOver="JavaScript code". Thus, you add this attribute into the tag that defines the link, modifying the example as follows:
<A HREF="url to link to" onMouseOver="JavaScript code">Text to appear highlighted in page</A>
Let's consider the portion of the preceding that you've been labeling "JavaScript code", which follows the onEvent= portion of the attribute. What should go in there?
The first rule is that you must include the surrounding double-quotes as previously written. So, no matter what, the event watcher must say onEvent="somethingsomething". The actions specified between the double quotes are known as the event handler. This makes sense, because they describe how to handle the event, once triggered. The event handler is your JavaScript program code.
You would call basically two types of JavaScript event handlers between those double quotes: the function call and explicit code.
The function call is the most common, and most desirable, event handler. This is why functions are so useful. In a nicely constructed web page, you define each function intended to handle a particular event at the top of the page, in the <HEAD> section. Then, in the course of the page, you call each function as required by your event watchers (the onEvent attributes).
In the case of a function call event handler, the previous link example might resemble this:
<A HREF="http://www.yahoo.com" onMouseOver="myfunction(parameter)">Text to appear highlighted in page</A>
In this example, when a user positions the mouse pointer over the link (which would bring him to http://www.yahoo.com if he actually clicked on it), the JavaScript function myfunction(parameter) is called.
Important parameter bulletin: Note that the onEvent attribute requires double quotation marks around its definition. This means that if you want to send a string literal as a parameter in the function call, you cannot use double quotation marks to specify the literal. For example, imagine you want to call printfancy ("Nice work!") as the event handler. You have to use single quotes for the string literal; otherwise, they'll be misinterpreted as the close of the onEvent attribute. Thus, you have to write onEvent="printfancy ('Nice work!')". Something to keep in mind.
Besides the elegant solution of a function call, you can write out explicit JavaScript statements within the double quotes. You can write an entire JavaScript program, of any length, although 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:
- You cannot use any double quotation marks. You're limited to using single quotes
( ' ) anywhere a quotation mark is needed, because a double quotation mark ( " ) would be interpreted as closing the onEvent attribute.
- Separate each JavaScript statement from the others with a semicolon.
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.
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"></SCRIPT> tags, and those functions may then be called normally as event handlers in the onEvent attribute.
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, we'll now run through examples of event triggers for some more types of events. Although they all follow the same rules outlined thus far, it's nice to see how a specific event is handled, to refer back to later on. Also, this chapter could use a couple more pages.
Imagine that users will click on a check box indicating their marital status. Upon clicking-whether they check it on or off-you may want to trigger a JavaScript function that uses their marital status in some other calculation. Keep in mind that forms are defined with <FORM> tags in HTML; however, the specifics of that are not the subject of this book. Assuming you know how to define a form element, the following is the line that defines the check box and onClick event trigger:
<INPUT name=married TYPE="checkbox" onClick="marstat(this.checked)">Married?
The preceding line first defines a check box, as per conventional HTML standards. Then you include the onClick attribute, as discussed in this chapter. Note that you make a function call as the event handler. Presumably, you defined the JavaScript function "marstat()" earlier in the page. So far, this is just like previous examples of event triggers.
What might strike you as different, upon first glance, is the fact that you pass the parameter this.checked to the function marstat(). What is this.checked? It's composed of two parts-this and checked-so let's consider each, as this concept will reappear in subsequent examples. The above is a form, and, after all, it is the data entered into this form that you want to pass to our event-handling function. A form is considered an object in JavaScript. Recall that an object possesses a set of properties. The form above happens to be a check box form, and, therefore, as far as JavaScript is concerned, a check box object. The check box object is a built-in JavaScript object, which contains four properties, one of which is named checked. The checked property is a Boolean value indicating whether the check box is checked on (true) or off (false).
Therefore, this.checked refers to the property checked, which is part of the object
"this form," which happens to be a check box object. So in the previous function call, this.checked represents a Boolean value reflecting the state of the check box, and that is the parameter that the JavaScript function marstat desires.
In this case, you will plant an event trigger that will occur if the user moves the page focus to this form. Our form will be a simple one-line entry blank, but that doesn't matter-this action is triggered by the activation of this form element, not what data is placed into it. When focus is placed on this element, an explicit JavaScript statement is executed.
<INPUT NAME=age TYPE="" ROWS=1 SIZE="3" onFocus="window.status='Nice _focus'">Your age?
Again, you watch for and trigger this event just as in all previous examples. Instead of calling a JavaScript function upon triggering, you execute a JavaScript statement. In this case, you assign a string value (note the single quotation marks) to an object property. We won't cover the window object until the next chapter, but for now, just note that this particular JavaScript statement will cause the specific string value to appear in the Web browser's status line.
In this example, you'll watch for the user attempting to submit a form. Perhaps you offered a text box for the user to enter an e-mail address. After entering the address, the user then must hit the Submit button-typical HTML form design. Perhaps you wrote a JavaScript function that can look at the information the user entered and determine whether it is a plausible e-mail address (that is, has the proper format for an e-mail address). The following will trigger this hypothetical function, evalform (address), when the user attempts to submit the form.
<FORM onSubmit="evalform(this.email.value)">
<INPUT NAME=email TYPE="text" ROWS=1 SIZE="20">Enter your e-mail address
<INPUT NAME=submit TYPE="submit">
<INPUT NAME=reset TYPE="reset">
</FORM>
Alrighty then--as this is the final onEvent example, it's the most complicated. Let's tease this beast apart and see what's going on up there. For now, completely ignore the onSubmit attribute-we'll consider that last. Everything else should look like a typical HTML form. After the <FORM> tag, you define a text entry blank that is one row high and 20 spaces wide. You name this element email, as you see in the NAME= attribute. This name does not appear on the screen; it is for program reference only. The text following the <INPUT> tag will appear on the screen beside the element. Again, this is standard HTML form syntax.
Below that line, you then create another element, which is a Submit button, and below that you create a Reset button, in case the user wants to clear the text-entry element. Now, look at the event handling in this form, which is defined in the opening <FORM> tag. Because you want to call your function when the user submits the form via the Submit button, you use an onSubmit event watcher. Then, as per the previous examples, you define the event handler as a function call to the function evalform(). This should be familiar territory by now. What's worth special note is the syntax of the parameter you are sending to the evalform() function. The evalform() function-if it existed-would accept the user's input into the text-entry element of the form and determine whether it's a plausible e-mail address. You refer to this data with the name this.email.value.
Why? this, as usual, refers to the main object in question-this form. The text-entry element is a property of this form, and it is named whatever you named it with the NAME= attribute. (Psst--you named it email.) Finally, email itself (the text-entry element) is also an object-another built-in JavaScript object (the text-entry form element is a built-in object, which you named email within this particular page). One of the properties of the text element object is value, which contains the actual data entered into the element. So there it is: this.email.value refers to the data entered into the text element named email, which is a property of "this" form in question.
The preceding will pass the correct user input to the function evalform(parameter). This function should then return a true or false value upon making its evaluation-that is, with the JavaScript statement return true or return false as the last statement in the function definition. If a value true is returned, the submission will proceed in whatever manner you intend to handle it (usually this is done with the METHOD= attribute of the <FORM> tag, but you didn't include this here because it is the stuff of HTML coding, not JavaScript). If a false value is returned, the submission will not proceed.
The Least You Need To Know
Once again, reading the full chapter is an excellent idea. The following is a fair summary, but far from detailed instruction.
- Anywhere you place JavaScript code within an HTML document, it must reside between <SCRIPT> </SCRIPT> tags.
- Include all JavaScript function definitions within <SCRIPT> tags, within the <HEAD> section of the document (that is, all the way near the top).
- An event is any user action such as a click, mouse movement, text selection, or form entry.
- Event handlers are the JavaScript programs that execute upon being triggered by a specified event.
- Event handlers can be triggered using the onEvent="javascript code" attribute within the tag defining the element being watched.
- Events that can be triggered include onClick, onFocus, onBlur, onChange, onMouseOver, onSelect, and onSubmit.



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.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.