Полезная информация

Table of Contents | Previous | Next | Index

Chapter 10
Handling Events

JavaScript applications in Navigator are largely event-driven. Events are actions that occur usually as a result of something the user does. For example, clicking a button is an event, as is changing a text field or moving the mouse over a link. For your script to react to an event, you define event handlers, such as onChange and onClick.

This chapter contains the following sections:

Event handling changed significantly between JavaScript 1.1 and JavaScript 1.2. JavaScript 1.2 added:

For a good introduction to event handling in JavaScript 1.2, see the article Getting Ready for JavaScript 1.2 Events in the online View Source magazine. In addition, the JavaScript technical notes contain information on programming events.

JavaScript supports the events summarized in the following table.

Table 10.1 JavaScript event handlers  
Event Applies to Occurs when Event handler


User aborts the loading of an image (for example by clicking a link or clicking the Stop button)


windows and all form elements

User removes input focus from window or form element


text fields, textareas, select lists

User changes value of element


buttons, radio buttons, checkboxes, submit buttons, reset buttons, links

User clicks form element or link



User drops an object onto the browser window, such as dropping a file on the browser window


images, windows

The loading of a document or image causes an error


windows and all form elements

User gives input focus to window or form element


documents, images, links, text areas

User depresses a key


documents, images, links, text areas

User presses or holds down a key


documents, images, links, text areas

User releases a key


document body

User loads the page in the Navigator


documents, buttons, links

User depresses a mouse button


nothing by default

User moves the cursor


areas, links

User moves cursor out of a client-side image map or link



User moves cursor over a link


documents, buttons, links

User releases a mouse button



User or script moves a window



User resets a form (clicks a Reset button)



User or script resizes a window


text fields, textareas

User selects form element's input field



User submits a form


document body

User exits the page


Defining an Event Handler

You define an event handler (a JavaScript function or series of statements) to handle an event. If an event applies to an HTML tag (that is, the event applies to the JavaScript object created from that tag), then you can define an event handler for it. The name of an event handler is the name of the event, preceded by "on." For example, the event handler for the focus event is onFocus.

To create an event handler for an HTML tag, add an event handler attribute to the tag. Put JavaScript code in quotation marks as the attribute value. The general syntax is

<TAG eventHandler="JavaScript Code">
where TAG is an HTML tag, eventHandler is the name of the event handler, and JavaScript Code is a sequence of JavaScript statements.

For example, suppose you have created a JavaScript function called compute. You make Navigator call this function when the user clicks a button by assigning the function call to the button's onClick event handler:

<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
You can put any JavaScript statements as the value of the onClick attribute. These statements are executed when the user clicks the button. To include more than one statement, separate statements with semicolons (;).

Notice in the preceding example this.form refers to the current form. The keyword this refers to the current object, which is the button. The construct this.form then refers to the form containing the button. The onClick event handler is a call to the compute function, with the current form as the argument.

When you create an event handler, the corresponding JavaScript object gets a property with the name of the event handler in lower case letters. (In JavaScript 1.2, you can also use the mixed case name of the event handler for the property name.) This property allows you to access the object's event handler. For example, in the preceding example, JavaScript creates a Button object with an onclick property whose value is "compute(this.form)".

Be sure to alternate double quotation marks with single quotation marks. Because event handlers in HTML must be enclosed in quotation marks, you must use single quotation marks to delimit string arguments. For example:

<INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!"
   onClick="window.open('mydoc.html', 'newWin')">
In general, it is good practice to define functions for your event handlers instead of using multiple JavaScript statements:

Example: Using an Event Handler

In the form shown in the following figure, you can enter an expression (for example, 2+2) in the first text field, and then click the button. The second text field then displays the value of the expression (in this case, 4).

Figure 10.1   Form with an event handler

The script for this form is as follows:

<!--- Hide script from old browsers
function compute(f) {
   if (confirm("Are you sure?"))
      f.result.value = eval(f.expr.value)
      alert("Please come back again.")
// end hiding from old browsers -->
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
<INPUT TYPE="text" NAME="result" SIZE=15 >
The HEAD of the document defines a single function, compute, taking one argument, f, which is a Form object. The function uses the window.confirm method to display a Confirm dialog box with OK and Cancel buttons.

If the user clicks OK, then confirm returns true, and the value of the result text field is set to the value of eval(f.expr.value). The JavaScript function eval evaluates its argument, which can be any string representing any JavaScript expression or statements.

If the user clicks Cancel, then confirm returns false and the alert method displays another message.

The form contains a button with an onClick event handler that calls the compute function. When the user clicks the button, JavaScript calls compute with the argument this.form that denotes the current Form object. In compute, this form is referred to as the argument f.

Calling Event Handlers Explicitly

In JavaScript 1.1 and later releases, you can reset an event handler specified by HTML, as shown in the following example.

function fun1() {
function fun2() {
<FORM NAME="myForm">
<INPUT TYPE="button" NAME="myButton"
Note that event handlers are function references, so you must assign fun2 itself, not fun2() (the latter calls fun2 and has whatever type and value fun2 returns).

Also, because the event handler HTML attributes are literal function bodies, you cannot use <INPUT onClick=fun1> in the HTML source to make fun1 the onClick handler for an input. Instead, you must set the value in JavaScript, as in the example.

Finally, because JavaScript is case-sensitive, in JavaScript 1.1 and earlier versions you must spell event handler names in lowercase in JavaScript. In JavaScript 1.2, you can also use the mixed case version of the name.

The Event Object

In JavaScript 1.2, each event has an associated event object. The event object provides information about the event, such as the type of event and the location of the cursor at the time of the event. When an event occurs, and if an event handler has been written to handle the event, the event object is sent as an argument to the event handler.

In the case of a MouseDown event, for example, the event object contains the type of event (in this case "MouseDown"), the x and y position of the mouse cursor at the time of the event, a number representing the mouse button used, and a field containing the modifier keys (Control, Alt, Meta, or Shift) that were depressed at the time of the event. The properties of the event object vary from one type of event to another, as described in the Client-Side JavaScript Reference.

Event Capturing

Typically, the object on which an event occurs handles the event. For example, when the user clicks a button, it is often the button's event handler that handles the event. Sometimes you may want the window or document object to handle certain types of events instead of leaving them for the individual parts of the document. For example, you may want the document object to handle all MouseDown events no matter where they occur in the document.

In JavaScript 1.2, JavaScript's event capturing model allows you to define methods that capture and handle events before they reach their intended target. To accomplish this, the window, document, and layer objects use these event-specific methods:

As an example, suppose you wanted to capture all click events occurring in a window.

NOTE: If a window with frames wants to capture events in pages loaded from different locations, you need to use captureEvents in a signed script and call enableExternalCapture. For information on signed scripts, see Chapter 14, "JavaScript Security."
Briefly, the steps for setting up event capturing are:

  1. Enable Event Capturing
  2. Define the Event Handler
  3. Register the Event Handler
The following sections explain these steps.

Enable Event Capturing

To set up the window to capture all Click events, use a statement such as the following:

The argument to captureEvents is a property of the event object and indicates the type of event to capture. To capture multiple events, the argument is a list separated by or (|). For example, the following statement captures Click, MouseDown, and MouseUp events:

window.captureEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP)

Define the Event Handler

Next, define a function that handles the event. The argument e is the event object for the event.

function clickHandler(e) {
   //What goes here depends on how you want to handle the event.
   //This is described below.
You have the following options for handling the event:

Register the Event Handler

Finally, register the function as the window's event handler for that event:

window.onClick = clickHandler;

A Complete Example

In the following example, the window and document capture and release events:

function fun1(e) {
   alert ("The window got an event of type: " + e.type +
      " and will call routeEvent.");
   alert ("The window returned from routeEvent.");
   return true;
function fun2(e) {
   alert ("The document got an event of type: " + e.type);
   return false;
function setWindowCapture() {
function releaseWindowCapture() {
function setDocCapture() {
function releaseDocCapture() {

Validating Form Input

One of the most important uses of JavaScript is to validate form input to server-based programs such as server-side JavaScript applications or CGI programs. This is useful because

Generally, you'll want to validate input in (at least) two places:

The JavaScript page on DevEdge contains pointers to sample code. One such pointer is a complete set of form validation functions. This section presents some simple examples, but you should check out the samples on DevEdge.

Example Validation Functions

The following are some simple validation functions.

function isaPosNum(s) {
   return (parseInt(s) > 0)
function qty_check(item, min, max) {
   var returnVal = false
   if (!isaPosNum(item.value))
      alert("Please enter a positive number")
   else if (parseInt(item.value) < min)
      alert("Please enter a " + item.name + " greater than " + min)
   else if (parseInt(item.value) > max)
      alert("Please enter a " + item.name + " less than " + max)
      returnVal = true
   return returnVal
function validateAndSubmit(theform) {
   if (qty_check(theform.quantity, 0, 999)) {
      alert("Order has been Submitted")
      return true
   else {
      alert("Sorry, Order Cannot Be Submitted!")
      return false
isaPosNum is a simple function that returns true if its argument is a positive number, and false otherwise.

qty_check takes three arguments: an object corresponding to the form element being validated (item) and the minimum and maximum allowable values for the item (min and max). It checks that the value of item is a number between min and max and displays an alert if it is not.

validateAndSubmit takes a Form object as its argument; it uses qty_check to check the value of the form element and submits the form if the input value is valid. Otherwise, it displays an alert and does not submit the form.

Using the Validation Functions

In this example, the BODY of the document uses qty_check as an onChange event handler for a text field and validateAndSubmit as the onClick event handler for a button.

<FORM NAME="widget_order" ACTION="lwapp.html" METHOD="post">
How many widgets today?
<INPUT TYPE="text" NAME="quantity" onChange="qty_check(this, 0, 999)">
<INPUT TYPE="button" VALUE="Enter Order" onClick="validateAndSubmit(this.form)">
This form submits the values to a page in a server-side JavaScript application called lwapp.html. It also could be used to submit the form to a CGI program. The form is shown in the following figure.

Figure 10.2   A JavaScript form

The onChange event handler is triggered when you change the value in the text field and move focus from the field by either pressing the Tab key or clicking the mouse outside the field. Notice that both event handlers use this to represent the current object: in the text field, it is used to pass the JavaScript object corresponding to the text field to qty_check, and in the button it is used to pass the JavaScript Form object to validateAndSubmit.

To submit the form to the server-based program, this example uses a button that calls validateAndSubmit, which submits the form using the submit method, if the data are valid. You can also use a submit button (defined by <INPUT TYPE="submit">) and then put an onSubmit event handler on the form that returns false if the data are not valid. For example,

<FORM NAME="widget_order" ACTION="lwapp.html" METHOD="post" 
   onSubmit="return qty_check(theform.quantity, 0, 999)">
<INPUT TYPE="submit">
When qty_check returns false if the data are invalid, the onSubmit handler will prohibit the form from being submitted.

Table of Contents | Previous | Next | Index

Last Updated: 11/06/98 10:47:23

Copyright (c) 1998 Netscape Communications Corporation