Previous Page TOC Next Page See Page



- 6 -
Event Processing


To take full advantage of the powerful capabilities provided by Client JavaScript, you need to understand how Netscape Navigator handles events.

Events are basically special signals, or messages, which "occur" when certain pre-defined actions take place within a Web browser, or when a user interacts with a Web page.

This chapter examines the types of events that exist in Client JavaScript and also looks at how event handlers can programmatically intercept these event messages. The topics to be discussed include the following:


The Netscape Navigator Event Model


Unlike procedural programming languages, which execute their instructions in a predetermined order—traditionally starting with the first instruction and working through to the last—languages like JavaScript have been designed so that they don't need a pre-defined starting or ending point.

Through the use of messaging systems, (or events, in the case of JavaScript) such languages can be made to execute sets of instructions that react to user requests and actions that have no pre-determined order or flow.

For example, when a new document is loaded into Netscape Navigator a load event message is triggered by JavaScript, indicating when the Web page has been completely loaded. This message can then be intercepted by a JavaScript program with an event handler, which can be programmed to react to the loading of the new page in some way.

Event Types


The types of events currently recognized by JavaScript fall into one of five basic categories. The following list briefly outlines what each of the categories are. Later in the chapter each of the specific events and their handlers are examined in more detail.

Document based events These events are triggered whenever a new page is loaded or an old page is exited. They include the load event and the unload event.
Form based events These event are triggered when a user interacts with a form on a Web page. They include the focus, blur, change select, and submit events.
Anchor based events Whenever a user clicks on a hyperlink in a Web page, an anchor based event is triggered. Anchor based events include the click and mouseover events.
Element based events These events communicate the status of images associated with a Web page. They include the load, error, and abort events.
Window based events Whenever more that one window is displayed by Netscape Navigator, window based events are used to indicate which window is currently active. They include the blur and focus event.

Event Handlers


Once an event message has been triggered, you need a way to intercept the message and react to it. This is achieved in JavaScript through the use of event handlers.

Event handlers are a block of JavaScript commands that have been directly associated with an HTML tag that relates to the particular type of event you want to intercept. The basic syntax for an event handler follows:

<TAG ATTRIBUTES onEventHandler="JavaScript commands">

The TAG represents an HTML tag supporting a particular category of events, and onEventHandler is the name of the event you want to intercept. The JavaScript commands that you want to execute when this event messages is activated are placed inside the quotes following the equal sign.

For example, to intercept the document load event and display an alert message indicating when a Web page has loaded, you would write

<BODY onLoad="window.alert('Page Loaded');">
  Your Web page contents go here.
</BODY>

Figure 6.1. The onLoad event handler can trigger an alert message to tell you when a Web page is completely loaded.

In this example, the <BODY> document tag includes an onLoad event handler to intercept the document load event message. When this message is triggered, the JavaScript statement window.alert ('Page Loaded') is executed, causing an alert box like the one shown in Figure 6.1 to be displayed.

If you want an event handler to execute more that one command, you can include all the commands inside the quotes, separating each instruction with a semicolon:

<BODY onLoad="window.alert('Page Loaded'); count = count + 1; ">

An alternative method is to call you own pre-defined functions or methods:

<BODY onLoad="myFunction();">

this keyword


The this keyword—mentioned in previous chapters—takes on a special significance when it is associated with events and event handlers. Take for example the following statement:

<BODY onLoad="myFunction( this );">

When the term this is used inside a event handler, it represents an alias, or pointer, to the object directly associated with the current tag. In this case, this points to the window object for the current document.

Document Based Events


As you have already read, document based events are sent whenever a new Web page is loaded or when an old web page is exited. Specifically, the two events that are generated for documents are the load event, which occurs whenever a new page is loaded, and the unload event, which occurs whenever a page is exited.

There are two HTML tags that can be associated with document based events. These are the <BODY> tag and the <FRAMESET> tag. (A detailed discussion of the FRAMESET tag can be found in Chapter Eight, "Frames and JavaScript.")

onLoad Event Handler


When attached to a <BODY> tag, the onLoad event handler is called once a Web page have been completely loaded. To include an onLoad event handler in a <BODY> tag, you would write something like the following:

<BODY onLoad="window.alert("Welcome to the World's best Web page");">

Alternatively, when attached to a <FRAMESET> tag, the onLoad event handler is called once the entire frameset has been completely loaded. When included in a <FRAMESET> tag, the onLoad event handler takes the following form:

<FRAMESET ROWS="*,*" onLoad="myFunct("frameset loaded");">
   <FRAME . . .>
   <FRAME . . .>
</FRAMESET>


Note

It is important to understand that the load event is not triggered when the Web page is first displayed, but instead when all elements (including images, applets, and plug-ins) are fully loaded and displayed.



onUnload Event Handler


When attached to a <BODY> tag, the onUnload event handler is called as a Web page is exited, either by loading a new Web page or by closing the Navigator program. The onUnload event handler is included in the <BODY> in much the same way as the onLoad event handler:

<BODY onLoad="window.alert('welcome');" onUnload="window.alert('bye');">

This example also demonstrates that a document can have both an onLoad and an onUnload event handler associated with it at the same time.

Like the onLoad event handler, the onUnload event handler can also be associated with a <FRAMESET> tag, in which case the onUnload event handler is only called when the entire frameset is exited.

Form Based Events


One of the most useful functions associated with events in Client JavaScript is the ability is intercept actions taken by a user as they fill out information on a form.

Most of the HTML elements associated with forms support one or more event handlers, depending on the purpose of the element. Table 6.1 outlines each of the form elements and the event handlers they support. The following pages then examine the use of each event handler.

Table 6.1. Form Based Event Handlers in Client JavaScript.

Form Element Event Handlers Recognized
Button Element onClick
Checkbox onClick
Radio Button onClick
Selection List onBlur, onChange, onFocus
Text Element onBlur, onChange, onFocus, onSelect
Textarea Element onBlur, onChange, onFocus, onSelect
Reset Button onClick
Submit Button onClick
Form onSubmit


Note:

The following pages discuss the events that can be associated with the form tag and form fields, but do not examine in detail the process of programming forms. This discussion is left to Chapter Seven, "Working with Forms."



onFocus Event Handler


Consider the form shown in figure 6.2, which contains a number of separate fields where a user can enter information. When the user places the cursor into any of these fields, that field is said to be given focus. Once a field has focus, a user can type information into it.

When one field has the focus, all other fields on the form are said to be out of focus, or blurred.

Figure 6.2. A simple data entry form with focus on the Given Names field.

To help programmers keep track of which field is currently in focus, a focus event message is generated by JavaScript whenever a user enters a select, text, or textarea field. This focus event can be intercepted by including an onFocus event handler in any <INPUT> tag of type TEXT, in any <SELECT> tag, or any <TEXTAREA> tag. (See Chapter Seven for a full discussion of these tags.)

You declare an onFocus event handler for a text input field by writing the following:

<INPUT TYPE="TEXT" SIZE="2" NAME="Country" onFocus="SetCountry( this )">

In this example, whenever a user clicks on the Country field or attempts to enter it by any other means, the function SetCountry( this ) is automatically called. (In this case, this points to a text object that represents the Country field. See Chapter Seven for more details on developing interactive forms using JavaScript.

onBlur Event Handler


The blur event indicates the opposite action to that of a focus event. Whenever a user exits a select, text, or textarea field, a blur event is triggered. To intercept the blur event, an onBlur event handler can be associated with any <INPUT> tag of type TEXT, any <SELECT> tag, or <TEXTAREA> tag.

One of the main uses of the onBlur event handler is for validating the contents of a field once it has been entered. In the following example, a function called valid() is executed when the user exits the email field. The function is passed the value of the email field by using the statement this.value:

<INPUT TYPE="TEXT" SIZE="20" NAME="Email" onBlur="valid( this.value )">

onChange Event Handler


Whenever a user exits a select, text, or textarea field where the contents of the field have been altered, a change event is triggered. To intercept the change event, an onChange event handler can be associated with any <INPUT> tag of type TEXT, any <SELECT> tag, or any <TEXTAREA> tag.

Like the onBlur event handler, the main use of the onChange event handler is for validating the contents of a field once it has been entered. In the following example, a function called valid() is executed whenever the user exits the email field and the contents of the field have been altered:

<INPUT TYPE="TEXT" SIZE="20" NAME="Email" onChange="if (this.value == '') { alert('Please Enter a Value') }">

This event handler would produce results like those shown in Figure 6.3 if the user removes focus from the field without entering a value.

Figure 6.3. Using the onBlur event handler, it is possible to perform basic validation on form data.



Note:

Unlike Navigator 2.0, which only triggered a change event for select fields when the user exited the field, in Navigator 3.0, a change event is triggered for select fields the moment the value of the field is altered.



onClick Event Handler


Whenever a checkbox, radio button, submit or reset button, or a form button is clicked by the user, a click event is triggered. To intercept these click events, a onClick event handler can be associated with any <INPUT> tag of type BUTTON, CHECKBOX, RADIO, RESET, or SUBMIT.

For example, to detect when a user has clicked on the submit button of a form, you would write something like the following:

<INPUT TYPE="SUBMIT" VALUE="Submit Address" onClick="validate( this.form );">

In this example, the function validate() is executed whenever a user clicks on the Submit Address button. Also, the special alias this.form has been used to pass the current form object to the validate() function, instead of passing the submit object, which would have been the case if validate( this ) had been used.



Note:

By returning a value of false to an onClick handler, the action associated with a button can be canceled. For example, if the event handler code in the previous example had been written as onClick="return validate( this.form )" and the function validate() returned a value of false, the form submission would be canceled.



onSelect Event Handler


A select event occurs when a user selects or highlights any of the text within a text or textarea field. To intercept a select event, place an onSelect event handler in the appropriate TEXT type <INPUT> tag or <TEXTAREA> tag.

To incorporate an onSelect event handler into a <TEXTAREA> tag you would write the following:

<TEXTAREA NAME="TextItem" ROWS=6 COLS=55 onSelect="selectText()">
Selecting any of the text in this field
will cause a select event to be triggered.
</TEXTAREA>

Whenever a user selects any of the text in the TextItem field, the selectText() function indicated by the onSelect event handler is called.



Note:

The implementation of onSelect is currently unstable as of Navigator 3.0b3 and does not work as advertised on the windows platform.



onSubmit Event Handler


Unlike all of the other form based events which interact with specific fields on a form, the submit event is only available from within the <FORM> tag itself. When a user attempts to submit a form, a click event is first generated for the appropriate submit button. Once this event has been processed, a submit event is triggered.

To intercept a submit event, place an onSubmit event handler within the forms <FORM> tag, as shown in the following example:

<FORM METHOD="POST" NAME="myForm"
      ACTION="../cgi-bin/form"
      onSubmit="return valid( this );" >

In this example, a function called valid() is executed when a user attempts to submit the form. The function performs some processing to verify that the user has entered the correct information. If any information is wrong, valid() returns a result of false, otherwise it returns a true result. When a false result is returned by the onSubmit event handler, the submission process is aborted.



Note:

When this is used inside a <FORM> tag it refers to the form object itself and not to any single element, as was the case in previous examples.



Anchor Based Events


Anchor based events are caused by the user either clicking on a hyperlink within a web page or by moving the mouse cursor over the top of a hyperlink. Hyperlinks are defined using the <A> tag in HTML.

onClick Event Handler


Whenever a user clicks on a hyperlink within a Web page, a click event is triggered within JavaScript. To intercept this click event, you place a onClick event handler within the link tag:

<A HREF="some URL" onClick="someFunction();">This is a link</A>

One of the most common reasons for using an onClick handler with a hyperlink is to dynamically alter the destination of the link.

This can be easily achieved in JavaScript using a link like the following:

<A HREF="some URL" onClick="this.href = randomLink();">This is a link</A>

In this example, whenever the user clicks on the link, a function called randomLink() is executed. This function returns a URL which is then assigned to this.href—a property of the link object. Once this.href is set, the new link is opened, replacing the old Web page.

As was the case in the earlier discussion of onClick handlers for form based events, the click event for a hyperlink can also be canceled by returning a value of false to the onClick handler:

<A HREF="some URL" onClick="return someFunction();">This is a link</A>

If the function someFunction() returns a false value then the click event is canceled and no new page loaded.

onMouseOver Event Handler


When a user moves the mouse cursor over a hyperlink a mouseover event is triggered. To intercept a mouseover event, you place an onMouseOver event handler within with the link tag:

<A HREF="some URL" onMouseOver="someFunction();">This is a link</A>

One of the most common reasons for using an onMouseOver handler with a hyperlink is to display a message or description in the status line indicating the action performed by the link. To do this, you write the following:

<A HREF="some URL"
   onMouseOver="window.status='Click to load a new page'; return true;">
New Page</A>

In this example, whenever the user moves the mouse cursor over the top of the New Page link the message "Click to load a new page" is displayed in the status bar.



Note:

You must return a value of true to the onMouseOver event handler before any message can be displayed in the status bar. This is achieved by placing the statement return true; as the last command the event handler executes.



onMouseOut Event Handler


The mouseout event represents the opposite of the mouseover event. Where a mouseover event is triggered when a user moves the mouse cursor over a hyperlink, the mouseout event is triggered when the user moves the mouse cursor off the link again.

To intercept a mouseout event, you place an onMouseOut event handler within with the link tag:

<A HREF="some URL" onMouseOut="someFunction();">This is a link</A>

The most common reason for using an onMouseOut handler with a hyperlink is to remove a message or description from the status line that was put there by an onMouseOver event. To do this, you write the following:

<A HREF="some URL"
   onMouseOver ="window.status='Click to load a new page'; return true;"
   onMouseOut  ="window.status=''; return true;" >
New Page</A>

In this example, whenever the user moves the mouse cursor over the top of the New Page link, the message "Click to load a new page" is displayed in the status bar. When the cursor is moved away from the hyperlink, the onMouseOut event handler is triggered to remove the message from the status bar. These results look like those shown in Figure 6.4 and 6.5.

Figure 6.4. The onMouseOver event handler can be used to display text in the status bar when the mouse pointer moves over a link.

Figure 6.5. The onMouseOut event is used to react to the user moving the mouse pointer off of a link.



Note:

Like the onMouseOver event handler, you must return a value of true to the onMouseOut event handler before any message can be displayed in the status bar. This is achieved by placing the statement return true; as the last command the event handler executes.



Element Based Events


Any information displayed on a Web page other than text is treated by Netscape Navigator as a separate page element. In the current Navigator version these elements fall into one of three categories:

Because these elements are treated as separate entities from the rest of a Web page, it is often useful to know when each has completed loading. For this reason JavaScript includes a small set of element based event handlers which can be used to intercept element load events, load error events, and load abort events.

Presently, Navigator 3 supports these events for images.

onLoad Event Handler


Like the document load event which is triggered when an entire Web page is loaded, an element load event is triggered when the element it is associated with is fully loaded. To intercept the element load event for an image, you place an onLoad event handler in the element tag associated with the item you are interested in.

For example, to attach an onLoad event to an image you would write the following:

<IMG SRC="someimage.gif" HEIGHT="50" WIDTH="50" onLoad="someFunction();">

In this example, the function someFunction() is called once the image has been completely loaded.

onError Event Handler


An error event is triggered for an image if any problems occur while the image is being loaded. This could include not being able to access the required file, some software related difficulty, or possibly some form of version incompatibilities.

To intercept the error event for an image, place an onError event handler in the element tag associated with the item you are interested in.

For example, to attach an onError event to an image you would write the following:

<IMG SRC="someimage.gif" HEIGHT="50" WIDTH="50" onError="someFunction();">

In this example the function someFunction() is called only if there is an error while loading the image, which results in the image not being able to load completely.

onAbort Event Handler


Because Netscape navigator normally loads and displays the text contents of a Web page before any other elements are displayed, you sometimes encounter situations where other elements are never completely loaded, either because the user has clicked on the stop button or because a new hyperlink has been selected. In such cases an abort event is triggered for each image.

To intercept the image abort event place an onAbort event handler in the tag associated with the image you are interested in.

For example, to attach an onAbort event to an image, you would write the following:

<IMG SRC="someimage.gif" HEIGHT="50" WIDTH="50" onAbort="someFunction();">

In this example, the function someFunction() is called only if the loading of the specified image is stopped, either by the user clicking on the stop button, or because a new Web page has been selected.

Window Based Events


Because Netscape Navigator enables you to open more that one window at once, it is often very useful to know exactly which window is currently active, or, in other words, which window has focus. The two window based events discussed in this section enable you to keep track of when a window gains focus and when it loses it.

onFocus Event Handler


Whenever a window is activated, or brought into focus, a window focus event in triggered by JavaScript. This event can be intercepted by placing a window onFocus event handler in either the <BODY> tag of a single frame window or the <FRAMESET> tag of a frameset window.

For example, to assign the function myFunction() to the window onFocus event handler of the current browser window, you would write

<BODY onFocus=" myFunction();" >

Whenever the window containing this document gains focus the function myFunction() is automatically called.

onBlur Event Handler


When a window loses focus, a window blur event is triggered by JavaScript. This event can be intercepted by using a window onBlur event handler. To intercept a window blur event you place an onBlur event handler in either the <BODY> tag of a single frame window or the <FRAMESET> tag of a frameset window.

For example, to attach an onBlur event handler to a frameset you would write the following:

<FRAMESET ROWS="*,*" onBlur="myFunction();" >
   <FRAME . . .>
   <FRAME . . .>
</FRAMESET>

This command assigns the function myFunction() to the window onBlur event handler of the current browser window. Once set, whenever this window loses focus, myFunction() is called automatically.

Advanced Event Processing Options


In addition to defining event handlers by coding them into your HTML code, many handlers also can be maintained programmatically. This section examines the process of defining event handlers in JavaScript code, and looks at how event messages can be triggered by JavaScript commands.

Assigning Events by Code


Whenever you assign an event handler to a tag, what actually happens internally in the Web browser is that an event property of the object associated with the tag is set to contain the JavaScript code you defined in the event handler. See the following example:

<BODY onFocus="myFocusFunction();" onBlur="myBlurFunction();" >

Internally two properties of the window object are set, because window events are associated with the window object. In this case, window.onfocus is set equal to "myFocusFunct();" and window.onblur is set equal to "myBlurFunction();".

The fact that these properties exist means that you can set their contents using JavaScript code. For this reason, the event handlers in the previous <BODY> statement also could have been defined using the following JavaScript code:

<SCRIPT>
window.onfocus = myFocusFunction ;
window.onblur = myBlurFunction ;
</SCRIPT>

There are a few items to which you need to pay close attention. First, the name of the property is written in all lower case, so onFocus becomes onfocus. HTML code in not case specific, remember.

Second, when indicating which function should be called, you only write the function name and not the trailing parentheses. You need to do this so that the actual function is assigned to the event handler and not the result of a call to the function.

Objects Associated with Event Handlers

Table 6.2 lists all of the event handlers that can be set programmatically. It also lists the corresponding objects of the event handlers.



Some of these handlers are still under development as of Navigator 3.0b3, but most are expected in the final Navigator 3.0 release.

Table 6.2. Objects Associated with Event Handlers

Event Type Handler Object Example
Document onLoad document document.onload =

onUnload document document.onunload =
Form onSubmit form document.myform.onsubmit =

onBlur text document.myform.textname.onblur =

onBlur textarea document.myform.textaname.onblur =

onBlur select document.myform.selectname.onblur =

onChange text document.myform.textname.onchange =

onChange textarea document.myform.textaname.onchange =

onChange select document.myform.selectname.onchange =

onClick button document.myform.buttonname.onfocus =

onClick checkbox document.myform.checkname.onfocus =

onClick radio document.myform.radioname.onfocus =

onClick reset document.myform.resetname.onfocus =

onClick submit document.myform.submitname.onfocus =

onFocus text document.myform.textname.onfocus =

onFocus textarea document.myform.textaname.onfocus =

onFocus select document.myform.selectname.onfocus =

onSelect text document.myform.textname.onselect =

onSelect textarea document.myform.textaname.onselect =
Anchor onClick link document.links[0].onclick =

onMouseOver link document.links[0].onmouseover =

onMouseOut link document.links[0].onmouseout =
Element onAbort image document.images[0].onabort =

onAbort applet document.applets[0].onabort =

onAbort plugin navigator.plugins[0].onabort =

onError image document.images[0].onerror =

onError applet document.applets[0].onerror =

onError plugin navigator.plugins[0].onerror =

onLoad image document.images[0].onload =

onLoad applet document.applets[0].onload =

onLoad plugin navigator.plugins[0].onload =
Window onBlur window window.onblur =

onFocus window window.onfocus =


Note:

Refer to the online JavaScript guide provided by Netscape for the most up-to-date information on supported element handlers.



Triggering Events by Code


So far in this chapter, all of the discussions dealing with the triggering of events have indicated that the events were triggered by some user driven action, be it interaction with a form, selecting a link, or loading a new Web page. Most events are triggered by user driven action, but there is a way to trigger some of the events discussed in this chapter by using JavaScript program calls.

Take for example the blur and focus window events. Traditionally, these events are triggered when the user brings a new window into focus by clicking on a window. With the introduction of a window.blur() and window.focus() method to the window object, it is now possible to force a window into or out of focus using program calls.

If the method window.blur() is called from anywhere within a JavaScript program the window associated with the object is forced out of focus, sending it to the back of the screen on most platforms. Likewise, the window.focus() method can be called to force a window back into focus or to put it in different terms back to being the top window on the screen.

The follow list outlines the various methods that can be used to programmatically cause events to take place.

blur() The blur() method can be used with window, text, textarea, select, and password objects to force the given element out of focus.
focus() The focus() method can be used with window, text, textarea, select, and password objects to force the given element into focus.
select() When used with either a text, textarea, select, or password object, the select() methods causes all the text in the chosen field to be selected or highlighted.

The focus() and select() methods are often used together to programmatically select a field on a form and highlight its contents.

For example, if a field in a form has an onBlur event handler associated with it which calls a function validate( this ), the field can be forced back into focus and highlighted by using code like the following:

function validate( field ) {
if ( field == "" ) {
alert("You must complete the name field.")
field.focus()
field.select()
}
}
click() The click() methods enable you to simulate the clicking of a radio button, checkbox, form buttons, or the submit and reset buttons.

If click() is used with a radio button, the chosen radio button becomes the selected radio button. For checkboxes, the checkbox is toggled on and off. For buttons on a form, any action associated with the button is activated as though the user had selected it themselves.

As an example of using events programatically, the following code uses a hypertext link to submit the form name testForm:

<FORM NAME="testForm" METHOD="POST" ACTION="someURL">
<INPUT TYPE=text NAME="testField">
</FORM>
<A HREF="javascript:document.testForm.submit()">Submit Form</A>

Summary


Events and their corresponding event handlers form the basis of much of the interaction with a Web page that JavaScript makes possible. These event can be categorized into one of five categories: document based events, form based events, anchor based events, element based events and window based events.

To interact with any of the events in these five categories, you use what are called event handlers. Event handlers are blocks of JavaScript code that tell a JavaScript program how to react to events.

Now that you have an understanding of how events and event handlers work in JavaScript, you are better ready to understand the intricacies of work with forms. This topic is discussed in the next chapter.

Previous Page Page Top TOC Next Page See Page