Table of Contents | Previous | Next | Index


Chapter 3
Event Handlers

This chapter contains the event handlers that are used with client-side objects in JavaScript to evoke particular actions.

For general information on event handlers, see the Client-Side JavaScript Guide.

The following table summarizes the event handlers. 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.

Table 3.1 Event handlers
Event Event handler Description
Abort
onAbort

Executes JavaScript code when the user aborts the loading of an image.

Blur
onBlur

Executes JavaScript code when a form element loses focus or when a window or frame loses focus.

Change
onChange

Executes JavaScript code when a Select, Text, or Textarea field loses focus and its value has been modified

Click
onClick

Executes JavaScript code when an object on a form is clicked.

DblClick
onDblClick

Executes JavaScript code when the user double-clicks a form element or a link.

DragDrop
onDragDrop

Executes JavaScript code when the user drops an object onto the browser window, such as dropping a file.

Error
onError

Executes JavaScript code when the loading of a document or image causes an error.

Focus
onFocus

Executes JavaScript code when a window, frame, or frameset receives focus or when a form element receives input focus.

KeyDown
onKeyDown

Executes JavaScript code when the user depresses a key.

KeyPress
onKeyPress

Executes JavaScript code when the user presses or holds down a key.

KeyUp
onKeyUp

Executes JavaScript code when the user releases a key.

Load
onLoad

Executes JavaScript code when the browser finishes loading a window or all frames within a FRAMESET tag.

MouseDown
onMouseDown

Executes JavaScript code when the user depresses a mouse button.

MouseMove
onMouseMove

Executes JavaScript code when the user moves the cursor.

MouseOut
onMouseOut

Executes JavaScript code each time the mouse pointer leaves an area (client-side image map) or link from inside that area or link.

MouseOver
onMouseOver

Executes JavaScript code once each time the mouse pointer moves over an object or area from outside that object or area.

MouseUp
onMouseUp

Executes JavaScript code when the user releases a mouse button.

Move
onMove

Executes JavaScript code when the user or script moves a window or frame.

Reset
onReset

Executes JavaScript code when a user resets a form (clicks a Reset button).

Resize
onResize

Executes JavaScript code when a user or script resizes a window or frame.

Select
onSelect

Executes JavaScript code when a user selects some of the text within a text or textarea field.

Submit
onSubmit

Executes JavaScript code when a user submits a form.

Unload
onUnload

Executes JavaScript code when the user exits a document.


onAbort

Executes JavaScript code when an abort event occurs; that is, when the user aborts the loading of an image (for example by clicking a link or clicking the Stop button).

Event handler for

Image

Implemented in

JavaScript 1.1

Syntax

onAbort="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

Examples

In the following example, an onAbort handler in an Image object displays a message when the user aborts the image load:

<IMG NAME="aircraft" SRC="f15e.gif"
   onAbort="alert('You didn\'t get to see the image!')">

See also

event, onError, onLoad


onBlur

Executes JavaScript code when a blur event occurs; that is, when a form element loses focus or when a window or frame loses focus.

Event handler for

Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, window

Implemented in

JavaScript 1.0

JavaScript 1.1: event handler of Button, Checkbox, FileUpload, Frame, Password, Radio, Reset, Submit, and window

Syntax

onBlur="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Description

The blur event can result from a call to the window.blur method or from the user clicking the mouse on another object or window or tabbing with the keyboard.

For windows, frames, and framesets, onBlur specifies JavaScript code to execute when a window loses focus.

A frame's onBlur event handler overrides an onBlur event handler in the BODY tag of the document loaded into frame.

NOTE: In JavaScript 1.1, on some platforms placing an onBlur event handler in a FRAMESET tag has no effect.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

Examples

Example 1: Validate form input. In the following example, userName is a required text field. When a user attempts to leave the field, the onBlur event handler calls the required function to confirm that userName has a legal value.

<INPUT TYPE="text" VALUE="" NAME="userName"
   onBlur="required(this.value)">
Example 2: Change the background color of a window. In the following example, a window's onBlur and onFocus event handlers change the window's background color depending on whether the window has focus.

<BODY BGCOLOR="lightgrey"
   onBlur="document.bgColor='lightgrey'"
   onFocus="document.bgColor='antiquewhite'">
Example 3: Change the background color of a frame. The following example creates four frames. The source for each frame, onblur2.htm has the BODY tag with the onBlur and onFocus event handlers shown in Example 1. When the document loads, all frames are light grey. When the user clicks a frame, the onFocus event handler changes the frame's background color to antique white. The frame that loses focus is changed to light grey. Note that the onBlur and onFocus event handlers are within the BODY tag, not the FRAME tag.

<FRAMESET ROWS="50%,50%" COLS="40%,60%">
<FRAME SRC=onblur2.htm NAME="frame1">
<FRAME SRC=onblur2.htm NAME="frame2">
<FRAME SRC=onblur2.htm NAME="frame3">
<FRAME SRC=onblur2.htm NAME="frame4">
</FRAMESET>
The following code has the same effect as the previous code, but is implemented differently. The onFocus and onBlur event handlers are associated with the frame, not the document. The onBlur and onFocus event handlers for the frame are specified by setting the onblur and onfocus properties.

<SCRIPT>
function setUpHandlers() {
   for (var i = 0; i < frames.length; i++) {
      frames[i].onfocus=new Function("document.bgColor='antiquewhite'")
      frames[i].onblur=new Function("document.bgColor='lightgrey'")
   }
}
</SCRIPT>
<FRAMESET ROWS="50%,50%" COLS="40%,60%" onLoad=setUpHandlers()>
<FRAME SRC=onblur2.htm NAME="frame1">
<FRAME SRC=onblur2.htm NAME="frame2">
<FRAME SRC=onblur2.htm NAME="frame3">
<FRAME SRC=onblur2.htm NAME="frame4">
</FRAMESET>
Example 4: Close a window. In the following example, a window's onBlur event handler closes the window when the window loses focus.

<BODY onBlur="window.close()">
This is some text
</BODY>

See also

event, onChange, onFocus


onChange

Executes JavaScript code when a change event occurs; that is, when a Select, Text, or Textarea field loses focus and its value has been modified.

Event handler for

FileUpload, Select, Text, Textarea

Implemented in

JavaScript 1.0 event handler for Select, Text, and Textarea

JavaScript 1.1: added as event handler of FileUpload

Syntax

onChange="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Description

Use onChange to validate data after it is modified by a user.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

Examples

In the following example, userName is a text field. When a user changes the text and leaves the field, the onChange event handler calls the checkValue function to confirm that userName has a legal value.

<INPUT TYPE="text" VALUE="" NAME="userName" 
   onChange="checkValue(this.value)">

See also

event, onBlur, onFocus


onClick

Executes JavaScript code when a click event occurs; that is, when an object on a form is clicked. (A click event is a combination of the MouseDown and MouseUp events).

Event handler for

Button, document, Checkbox, Link, Radio, Reset, Submit

Implemented in

JavaScript 1.0

JavaScript 1.1: added the ability to return false to cancel the action associated with a click event

Syntax

onClick="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

When a link is clicked,
layerX, layerY,
pageX, pageY,
screenX, screenY

Represent the cursor location at the time the event occurred.

which

Represents 1 for a left-mouse click and 3 for a right-mouse click.

modifiers

Contains the list of modifier keys held down when the event occurred.

Description

For checkboxes, links, radio buttons, reset buttons, and submit buttons, onClick can return false to cancel the action normally associated with a click event.

For example, the following code creates a link that, when clicked, displays a confirm dialog box. If the user clicks the link and then chooses cancel, the page specified by the link is not loaded.

<A HREF = "http://home.netscape.com/"
   onClick="return confirm('Load Netscape home page?')">
Netscape</A>
If the event handler returns false, the default action of the object is canceled as follows:

NOTE: In JavaScript 1.1, on some platforms, returning false in an onClick event handler for a reset button has no effect.

Examples

Example 1: Call a function when a user clicks a button. Suppose you have created a JavaScript function called compute. You can execute the compute function when the user clicks a button by calling the function in the onClick event handler, as follows:

<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
In the preceding example, the keyword this refers to the current object; in this case, the Calculate button. The construct this.form refers to the form containing the button.

For another example, suppose you have created a JavaScript function called pickRandomURL that lets you select a URL at random. You can use onClick to specify a value for the HREF attribute of the A tag dynamically, as shown in the following example:

<A HREF=""
   onClick="this.href=pickRandomURL()"
   onMouseOver="window.status='Pick a random URL'; return true">
Go!</A>
In the above example, onMouseOver specifies a custom message for the browser's status bar when the user places the mouse pointer over the Go! anchor. As this example shows, you must return true to set the window.status property in the onMouseOver event handler.

Example 2: Cancel the checking of a checkbox. The following example creates a checkbox with onClick. The event handler displays a confirm that warns the user that checking the checkbox purges all files. If the user chooses Cancel, onClick returns false and the checkbox is not checked.

<INPUT TYPE="checkbox" NAME="check1" VALUE="check1"
   onClick="return confirm('This purges all your files. Are you sure?')"> Remove files

See also

event


onDblClick

Executes JavaScript code when a DblClick event occurs; that is, when the user double-clicks a form element or a link.

Event handler for

document, Link

Implemented in

JavaScript 1.2

Syntax

onDblClick="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

NOTE: DblClick is not implemented on the Macintosh.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

layerX, layerY,
pageX, pageY,
screenX, screenY

Represent the cursor location at the time the event occurred.

which

Represents 1 for a left-mouse double-click and 3 for a right-mouse double-click.

modifiers

Contains the list of modifier keys held down when the event occurred.

Examples

The following example opens an alert dialog box when a user double-clicks a button:

<form>
<INPUT Type="button" Value="Double Click Me!"
onDblClick="alert('You just double clicked me!')">
</form>

See also

event


onDragDrop

Executes JavaScript code when a DragDrop event occurs; that is, when the user drops an object onto the browser window, such as dropping a file.

Event handler for

window

Implemented in

JavaScript 1.2

Syntax

onDragDrop="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

data

Returns an Array of Strings containing the URLs of the dropped objects.

modifiers

Contains the list of modifier keys held down when the event occurred.

screenX,
screenY

Represent the cursor location at the time the event occurred.

Security

Getting the data property of the DragDrop event requires the UniversalBrowserRead privilege. For information on security, see the Client-Side JavaScript Guide.

Description

The DragDrop event is fired whenever a system item (file, shortcut, and so on) is dropped onto the browser window using the native system's drag and drop mechanism. The normal response for the browser is to attempt to load the item into the browser window. If the event handler for the DragDrop event returns true, the browser loads the item normally. If the event handler returns false, the drag and drop is canceled.

See also

event


onError

Executes JavaScript code when an error event occurs; that is, when the loading of a document or image causes an error.

Event handler for

Image, window

Implemented in

JavaScript 1.1

Syntax

onError="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Description

An error event occurs only when a JavaScript syntax or runtime error occurs, not when a browser error occurs. For example, if you try set window.location.href='notThere.htm' and notThere.htm does not exist, the resulting error message is a browser error message; therefore, onError would not intercept that message. However, an error event is triggered by a bad URL within an IMG tag or by corrupted image data.

window.onerror applies only to errors that occur in the window containing window.onerror, not in other windows.

onError can be any of the following:

If you write an error-handling function, you have three options for reporting errors:

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

Examples

Example 1: Null event handler. In the following IMG tag, the code onError="null" suppresses error messages if errors occur when the image loads.

<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2"
   onError="null">
Example 2: Null event handler for a window. The onError event handler for windows cannot be expressed in HTML. Therefore, you must spell it all lowercase and set it in a SCRIPT tag. The following code assigns null to the onError handler for the entire window, not just the Image object. This suppresses all JavaScript error messages, including those for the Image object.

<SCRIPT>
window.onerror=null
</SCRIPT>
<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2">
However, if the Image object has a custom onError event handler, the handler would execute if the image had an error. This is because window.onerror=null suppresses JavaScript error messages, not onError event handlers.

<SCRIPT>
window.onerror=null
function myErrorFunc() {
   alert("The image had a nasty error.")
}
</SCRIPT>
<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2"
   onError="myErrorFunc()">
In the following example, window.onerror=null suppresses all error reporting. Without onerror=null, the code would cause a stack overflow error because of infinite recursion.

<SCRIPT>
window.onerror = null;
function testErrorFunction() {
   testErrorFunction();
}
</SCRIPT>
<BODY onload="testErrorFunction()">
test message
</BODY>
Example 3: Error handling function. The following example defines a function, myOnError, that intercepts JavaScript errors. The function uses three arrays to store the message, URL, and line number for each error. When the user clicks the Display Error Report button, the displayErrors function opens a window and creates an error report in that window. Note that the function returns true to suppress the standard JavaScript error dialog.

<SCRIPT>
window.onerror = myOnError
msgArray = new Array()
urlArray = new Array()
lnoArray = new Array()
function myOnError(msg, url, lno) {
   msgArray[msgArray.length] = msg
   urlArray[urlArray.length] = url
   lnoArray[lnoArray.length] = lno
   return true
}
function displayErrors() {
   win2=window.open('','window2','scrollbars=yes')
   win2.document.writeln('<B>Error Report</B><P>')
   for (var i=0; i < msgArray.length; i++) {
      win2.document.writeln('<B>Error in file:</B> ' + urlArray[i] + '<BR>')
      win2.document.writeln('<B>Line number:</B> ' + lnoArray[i] + '<BR>')
      win2.document.writeln('<B>Message:</B> ' + msgArray[i] + '<P>')
   }
   win2.document.close()
}
</SCRIPT>
<BODY onload="noSuchFunction()">
<FORM>
<BR><INPUT TYPE="button" VALUE="This button has a syntax error"
   onClick="alert('unterminated string)">
<P><INPUT TYPE="button" VALUE="Display Error Report"
   onClick="displayErrors()">
</FORM>
This example produces the following output:

Error Report
Error in file: file:///c%7C/temp/onerror.htm
Line number: 34
Message: unterminated string literal
Error in file: file:///c%7C/temp/onerror.htm
Line number: 34
Message: missing ) after argument list
Error in file: file:///c%7C/temp/onerror.htm
Line number: 30
Message: noSuchFunction is not defined
Example 4: Event handler calls a function. In the following IMG tag, onError calls the function badImage if errors occur when the image loads.

<SCRIPT>
function badImage(theImage) {
   alert('Error: ' + theImage.name + ' did not load properly.')
}
</SCRIPT>
<FORM>
<IMG NAME="imageBad2" SRC="orca.gif" ALIGN="left" BORDER="2"
   onError="badImage(this)">
</FORM>

See also

event, onAbort, onLoad


onFocus

Executes JavaScript code when a focus event occurs; that is, when a window, frame, or frameset receives focus or when a form element receives input focus.

Event handler for

Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, window

Implemented in

JavaScript 1.0

JavaScript 1.1: event handler of Button, Checkbox, FileUpload, Frame, Password, Radio, Reset, Submit, and window

JavaScript 1.2: event handler of Layer

Syntax

onFocus="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Description

The focus event can result from a focus method or from the user clicking the mouse on an object or window or tabbing with the keyboard. Selecting within a field results in a select event, not a focus event. onFocus executes JavaScript code when a focus event occurs.

A frame's onFocus event handler overrides an onFocus event handler in the BODY tag of the document loaded into frame.

Note that placing an alert in an onFocus event handler results in recurrent alerts: when you press OK to dismiss the alert, the underlying window gains focus again and produces another focus event.

NOTE: In JavaScript 1.1, on some platforms, placing an onFocus event handler in a FRAMESET tag has no effect.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

Examples

The following example uses an onFocus handler in the valueField Textarea object to call the valueCheck function.

<INPUT TYPE="textarea" VALUE="" NAME="valueField"
   onFocus="valueCheck()">
See also the examples for onBlur.

See also

event, onBlur, onChange


onKeyDown

Executes JavaScript code when a KeyDown event occurs; that is, when the user depresses a key.

Event handler for

document, Image, Link, Textarea

Implemented in

JavaScript 1.2

Syntax

onKeyDown="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

layerX, layerY,
pageX, pageY,
screenX, screenY

For an event over a window, these represent the cursor location at the time the event occurred. For an event over a form, they represent the position of the form element.

which

Represents the ASCII value of the key pressed. To get the actual letter, number, or symbol of the pressed key, use the String.fromCharCode method. To set this property when the ASCII value is unknown, use the String.charCodeAt method.

modifiers

Contains the list of modifier keys held down when the event occurred.

Description

A KeyDown event always occurs before a KeyPress event. If onKeyDown returns false, no KeyPress events occur. This prevents KeyPress events occurring due to the user holding down a key.

Examples

The following example uses the blockA function to evaluate characters entered from the keyboard in the textentry text box. If a user enters either "a" or "A", the function returns false and the text box does not display the value.

<form name="main">
   <input name="textentry" type=text size=10 maxlength=10>
</form>

<script>
function blockA(e) {
var keyChar = String.fromCharCode(e.which);
if (keyChar == 'A' || keyChar == 'a')
return false;
}

document.main.textentry.onkeydown = blockA;
</script>
In the function, the which property of the event assigns the ASCII value of the key the user presses to the keyChar variable. The if statement evaluates keyChar and returns false for the specified characters.

See also

event, onKeyPress, onKeyUp


onKeyPress

Executes JavaScript code when a KeyPress event occurs; that is, when the user presses or holds down a key.

Event handler for

document, Image, Link, Textarea

Implemented in

JavaScript 1.2

Syntax

onKeyPress="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

layerX, layerY,
pageX, pageY,
screenX, screenY

For an event over a window, these represent the cursor location at the time the event occurred. For an event over a form, they represent the position of the form element.

which

Represents the ASCII value of the key pressed. To get the actual letter, number, or symbol of the pressed key, use the String.fromCharCode method. To set this property when the ASCII value is unknown, use the String.charCodeAt method.

modifiers

Contains the list of modifier keys held down when the event occurred.

Description

A KeyPress event occurs immediately after a KeyDown event only if onKeyDown returns something other than false. A KeyPress event repeatedly occurs until the user releases the key. You can cancel individual KeyPress events.

Examples

In this example, the captureEvents method catches keyboard input and the onKeyPress handler calls the blockA function to examine the keystrokes. If the keystrokes are "a" or "z", the function scrolls the Navigator window.

function blockA(e) {
var keyChar = String.fromCharCode(e.which);
if (keyChar == 'A' || keyChar == 'a')
self.scrollBy(10,10);

else if(keyChar == 'Z' || keyChar == 'z')
self.scrollBy(-10,-10);

else return false;
}
document.captureEvents(Event.KEYPRESS);
document.onkeypress = blockA;

See also

event, onKeyDown, onKeyUp


onKeyUp

Executes JavaScript code when a KeyUp event occurs; that is, when the user releases a key.

Event handler for

document, Image, Link, Textarea

Implemented in

JavaScript 1.2

Syntax

onKeyUp="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

layerX, layerY,
pageX, pageY,
screenX, screenY

For an event over a window, these represent the cursor location at the time the event occurred. For an event over a form, they represent the position of the form element.

which

Represents the ASCII value of the key pressed. To get the actual letter, number, or symbol of the pressed key, use the String.fromCharCode method. To set this property when the ASCII value is unknown, use the String.charCodeAt method.

modifiers

Contains the list of modifier keys held down when the event occurred.

Examples

In this example, the captureEvents method catches keyboard input and the onKeyUp handler calls the Key_Up function. An alert method within the function opens a dialog box to display the value of the keystroke.

function Key_Up(e) {
var keyChar = String.fromCharCode(e.which);
alert("Hold '" + keyChar +"' again for me, okay?");
}
document.onkeyup=Key_Up;
document.captureEvents(Event.KEYUP);

See also

event


onLoad

Executes JavaScript code when a load event occurs; that is, when the browser finishes loading a window or all frames within a FRAMESET tag.

Event handler for

Image, Layer, window

Implemented in

JavaScript 1.0

JavaScript 1.1: event handler of Image

Syntax

onLoad="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Description

Use the onLoad event handler within either the BODY or the FRAMESET tag, for example, <BODY onLoad="...">.

In a FRAMESET and FRAME relationship, an onLoad event within a frame (placed in the BODY tag) occurs before an onLoad event within the FRAMESET (placed in the FRAMESET tag).

For images, the onLoad event handler indicates the script to execute when an image is displayed. Do not confuse displaying an image with loading an image. You can load several images, then display them one by one in the same Image object by setting the object's src property. If you change the image displayed in this way, onLoad executes every time an image is displayed, not just when the image is loaded into memory.

If you specify an onLoad event handler for an Image object that displays a looping GIF animation (multi-image GIF), each loop of the animation triggers the onLoad event, and the event handler executes once for each loop.

You can use the onLoad event handler to create a JavaScript animation by repeatedly setting the src property of an Image object. See Image for information.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

width, height

For an event over a window, but not over a layer, these represent the width and height of the window.

Examples

Example 1: Display message when page loads. In the following example, the onLoad event handler displays a greeting message after a Web page is loaded.

<BODY onLoad="window.alert("Welcome to the Brave New World home page!")>
Example 2: Display alert when image loads. The following example creates two Image objects, one with the Image constructor and one with the IMG tag. Each Image object has an onLoad event handler that calls the displayAlert function, which displays an alert. For the image created with the IMG tag, the alert displays the image name. For the image created with the Image constructor, the alert displays a message without the image name. This is because the onLoad handler for an object created with the Image constructor must be the name of a function, and it cannot specify parameters for the displayAlert function.

<SCRIPT>
imageA = new Image(50,50)
imageA.onload=displayAlert
imageA.src="cyanball.gif"
function displayAlert(theImage) {
   if (theImage==null) {
      alert('An image loaded')
   }
   else alert(theImage.name + ' has been loaded.')
}
</SCRIPT>
<IMG NAME="imageB" SRC="greenball.gif" ALIGN="top"
   onLoad=displayAlert(this)><BR>
Example 3: Looping GIF animation. The following example displays an image, birdie.gif, that is a looping GIF animation. The onLoad event handler for the image increments the variable cycles, which keeps track of the number of times the animation has looped. To see the value of cycles, the user clicks the button labeled Count Loops.

<SCRIPT>
var cycles=0
</SCRIPT>
<IMG ALIGN="top" SRC="birdie.gif" BORDER=0
   onLoad="++cycles">
<INPUT TYPE="button" VALUE="Count Loops"
   onClick="alert('The animation has looped ' + cycles + ' times.')">
Example 4: Change GIF animation displayed. The following example uses an onLoad event handler to rotate the display of six GIF animations. Each animation is displayed in sequence in one Image object. When the document loads, !anim0.htm is displayed. When that animation completes, the onLoad event handler causes the next file, !anim1.htm, to load in place of the first file. After the last animation, !anim5.htm, completes, the first file is again displayed. Notice that the changeAnimation function does not call itself after changing the src property of the Image object. This is because when the src property changes, the image's onLoad event handler is triggered and the changeAnimation function is called.

<SCRIPT>
var whichImage=0
var maxImages=5
function changeAnimation(theImage) {
   ++whichImage
   if (whichImage <= maxImages) {
      var imageName="!anim" + whichImage + ".gif"
      theImage.src=imageName
   } else {
      whichImage=-1
      return
   }
}
</SCRIPT>
<IMG NAME="changingAnimation" SRC="!anim0.gif" BORDER=0 ALIGN="top"
   onLoad="changeAnimation(this)">
See also the examples for Image.

See also

event, onAbort, onError, onUnload


onMouseDown

Executes JavaScript code when a MouseDown event occurs; that is, when the user depresses a mouse button.

Event handler for

Button, document, Link

Implemented in

JavaScript 1.2

Syntax

onMouseDown="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

layerX, layerY,
pageX, pageY,
screenX, screenY

Represent the cursor location at the time the MouseDown event occurred.

which

Represents 1 for a left-mouse-button down and 3 for a right-mouse-button down.

modifiers

Contains the list of modifier keys held down when the MouseDown event occurred.

Description

If onMouseDown returns false, the default action (entering drag mode, entering selection mode, or arming a link) is canceled.

Arming is caused by a MouseDown over a link. When a link is armed it changes color to represent its new state.

Examples

This example lets users move an image on an HTML page by dragging it with the mouse. Your HTML code defines the image and positions it in a layer called container1. In your JavaScript code, event handlers set the position properties of container1 as users drag the image, creating the animation.

Using style sheets, the image is initially defined and positioned as follows:

<HEAD>
<STYLE type="text/css">
#container1 { position:absolute; left:200; top:200}
</STYLE>
</HEAD>

<BODY>
<P ID="container1">
<img src="backgrnd.gif" name="myImage" width=96 height=96>
</P>
</BODY>
In the previous HTML code, the ID attribute for the P element which contains the image is set to container1, making container1 a unique identifier for the paragraph and the image. The STYLE tag creates a layer for container1 and positions it.

The following JavaScript code defines onMouseDown, onMouseUp, and onMouseMove event handlers:

<SCRIPT>
container1.captureEvents(Event.MOUSEUP|Event.MOUSEDOWN);
container1.onmousedown=DRAG_begindrag;
container1.onmouseup=DRAG_enddrag;
var DRAG_lastX, DRAG_lastY, DRAG_dragging;
function DRAG_begindrag(e) {
if (e.which == 1) {
window.captureEvents(Event.MOUSEMOVE);
       window.onmousemove=DRAG_drag;
DRAG_lastX=e.pageX;
DRAG_lastY=e.pageY;
DRAG_dragging=true;
return false;
}
else {
/*Do any right mouse button processing here*/
return true;
}
}
function DRAG_enddrag(e) {
if (e.which == 1) {
window.releaseEvents(Event.MOUSEMOVE);
       window.onmousemove=null
DRAG_dragging=false;
return false;
}
else {
/*Do any right mouse button processing here*/
return true;
}
}
function DRAG_drag(e) {
if (DRAG_dragging) {
/*This function called only if MOUSEMOVEs are captured*/
moveBy(e.pageX-DRAG_lastX, e.pageY-DRAG_lastY);
DRAG_lastX = e.pageX;
DRAG_lastY = e.pageY;
return false;
}
else {
return true;
}
}
</SCRIPT>
In the previous code, the captureEvents method captures MouseUp and MouseDown events. The DRAG_begindrag and DRAG_enddrag functions are respectively called to handle these events.

When a user presses the left mouse button, the DRAG_begindrag function starts capturing MouseMove events and tells the DRAG_drag function to handle them. It then assigns the value of the MouseDown event's pageX property to DRAG_lastX, the value of the pageY property to DRAG_lastY, and true to DRAG_dragging.

The DRAG_drag function evaluates DRAG_dragging to make sure the MouseMove event was captured by DRAG_begindrag, then it uses the moveBy method to position the object, and reassigns values to DRAG_lastX and DRAG_lastY.

When the user releases the left mouse button, the DRAG_enddrag function stops capturing MouseMove events. DRAG_enddrag then makes sure no other functions are called by setting onmousemove to Null and DRAG_dragging to false.

See also

event


onMouseMove

Executes JavaScript code when a MouseMove event occurs; that is, when the user moves the cursor.

Event handler for

None

Implemented in

JavaScript 1.2

Syntax

onMouseMove="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event of

Because mouse movement happens so frequently, by default, onMouseMove is not an event of any object. You must explicitly set it to be associated with a particular object.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

layerX, layerY,
pageX, pageY,
screenX, screenY

Represent the cursor location at the time the MouseMove event occurred.

Description

The MouseMove event is sent only when a capture of the event is requested by an object. For information on events, see the Client-Side JavaScript Guide.

Examples

See the examples for onMouseDown.

See also

event, document.captureEvents


onMouseOut

Executes JavaScript code when a MouseOut event occurs; that is, each time the mouse pointer leaves an area (client-side image map) or link from inside that area or link.

Event handler for

Layer, Link

Implemented in

JavaScript 1.1

Syntax

onMouseOut="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Description

If the mouse moves from one area into another in a client-side image map, you'll get onMouseOut for the first area, then onMouseOver for the second.

Area tags that use onMouseOut must include the HREF attribute within the AREA tag.

You must return true within the event handler if you want to set the status or defaultStatus properties with onMouseOver.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

layerX, layerY,
pageX, pageY,
screenX, screenY

Represent the cursor location at the time the MouseOut event occurred.

Examples

See the examples for Link.

See also

event, onMouseOver


onMouseOver

Executes JavaScript code when a MouseOver event occurs; that is, once each time the mouse pointer moves over an object or area from outside that object or area.

Event handler for

Layer, Link

Implemented in

JavaScript 1.0

JavaScript 1.1: event handler of Area

Syntax

onMouseOver="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Description

If the mouse moves from one area into another in a client-side image map, you'll get onMouseOut for the first area, then onMouseOver for the second.

Area tags that use onMouseOver must include the HREF attribute within the AREA tag.

You must return true within the event handler if you want to set the status or defaultStatus properties with onMouseOver.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

layerX, layerY,
pageX, pageY,
screenX, screenY

Represent the cursor location at the time the MouseOver event occurred.

Examples

By default, the HREF value of an anchor displays in the status bar at the bottom of the browser when a user places the mouse pointer over the anchor. In the following example, onMouseOver provides the custom message "Click this if you dare."

<A HREF="http://home.netscape.com/"
   onMouseOver="window.status='Click this if you dare!'; return true">
Click me</A>
See onClick for an example of using onMouseOver when the A tag's HREF attribute is set dynamically.

See also the examples for Link.

See also

event, onMouseOut


onMouseUp

Executes JavaScript code when a MouseUp event occurs; that is, when the user releases a mouse button.

Event handler for

Button, document, Link

Implemented in

JavaScript 1.2

Syntax

onMouseUp="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event properties used

Property Description
type 

Indicates the type of event.

target 

Indicates the object to which the event was originally sent.

layerX, layerY,
pageX, pageY,
screenX, screenY

Represent the cursor location at the time the MouseUp event occurred.

which 

Represents 1 for a left-mouse-button up and 3 for a right-mouse-button up.

modifiers 

Contains the list of modifier keys held down when the MouseUp event occurred.

Description

If onMouseUp returns false, the default action is canceled. For example, if onMouseUp returns false over an armed link, the link is not triggered. Also, if MouseUp occurs over an unarmed link (possibly due to onMouseDown returning false), the link is not triggered.

NOTE: Arming is caused by a MouseDown over a link. When a link is armed it changes color to represent its new state.

Examples

See the examples for onMouseDown.

See also

event


onMove

Executes JavaScript code when a move event occurs; that is, when the user or script moves a window or frame.

Event handler for

window

Implemented in

JavaScript 1.2

Syntax

onMove="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event properties used

Property Description
type 

Indicates the type of event.

target 

Indicates the object to which the event was originally sent.

screenX, 
screenY

Represent the position of the top-left corner of the window or frame.

Examples

In this example, the open_now function creates the myWin window and captures Move events. The onMove handler calls another function which displays a message when a user moves myWin.

function open_now(){ 
var myWin;
myWin=window.open("","displayWindow","width=400,height=400,menubar=no,
location=no,alwaysRaised=yes");
var text="<html><head><title>Test</title></head>"
+"<body bgcolor=white><h1>Please move this window</h1></body>"
+"</html>";
myWin.document.write(text);
myWin.captureEvents(Event.MOVE);
myWin.onmove=fun2;
}
function fun2(){ 
alert("Hey you moved me!");
this.focus(); //'this' points to the current object
}

See also

event


onReset

Executes JavaScript code when a reset event occurs; that is, when a user resets a form (clicks a Reset button).

Event handler for

Form

Implemented in

JavaScript 1.1

Syntax

onReset="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Examples

The following example displays a Text object with the default value "CA" and a reset button. If the user types a state abbreviation in the Text object and then clicks the reset button, the original value of "CA" is restored. The form's onReset event handler displays a message indicating that defaults have been restored.

<FORM NAME="form1" onReset="alert('Defaults have been restored.')">
State:
<INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2"><P>
<INPUT TYPE="reset" VALUE="Clear Form" NAME="reset1">
</FORM>

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

See also

event, Form.reset, Reset


onResize

Executes JavaScript code when a resize event occurs; that is, when a user or script resizes a window or frame.

Event handler for

window

Implemented in

JavaScript 1.2

Syntax

onResize="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

width, height

Represent the width and height of the window or frame.

Description

This event is sent after HTML layout completes within the new window inner dimensions. This allows positioned elements and named anchors to have their final sizes and locations queried, image SRC properties can be restored dynamically, and so on.

Examples

In this example, the open_now function creates the myWin window and captures Resize events. The onResize handler calls the alert_me function which displays a message when a user resizes myWin.

function open_now(){ 
var myWin;
myWin=window.open("","displayWin","width=400,height=300,resizable=yes,
menubar=no,location=no,alwaysRaised=yes");
var text="<html><head><title>Test</title></head>"
+"<body bgcolor=white><h1>Please resize me</h1></body>"
+"</html>";
myWin.document.write(text);
myWin.captureEvents(Event.RESIZE);
myWin.onresize=alert_me;
}
function alert_me(){ 
alert("You resized me! \nNow my outer width: " + this.outerWidth +
"\n and my outer height: " +this.outerHeight);
this.focus();
}

See also

event


onSelect

Executes JavaScript code when a select event occurs; that is, when a user selects some of the text within a text or textarea field.

Event handler for

Text, Textarea

Implemented in

JavaScript 1.0

Syntax

onSelect="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

Examples

The following example uses onSelect in the valueField Text object to call the selectState function.

<INPUT TYPE="text" VALUE="" NAME="valueField" onSelect="selectState()">

See also

event


onSubmit

Executes JavaScript code when a submit event occurs; that is, when a user submits a form.

Event handler for

Form

Implemented in

JavaScript 1.0

Syntax

onSubmit="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Security

Submitting a form to a mailto: or news: URL requires the UniversalSendMail privilege. For information on security, see the Client-Side JavaScript Guide.

Description

You can use onSubmit to prevent a form from being submitted; to do so, put a return statement that returns false in the event handler. Any other returned value lets the form submit. If you omit the return statement, the form is submitted.

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

Examples

In the following example, onSubmit calls the validate function to evaluate the data being submitted. If the data is valid, the form is submitted; otherwise, the form is not submitted.

<FORM onSubmit="return validate(this)">
...
</FORM>
See also the examples for Form.

See also

event, Submit, Form.submit


onUnload

Executes JavaScript code when an unload event occurs; that is, when the user exits a document.

Event handler for

window

Implemented in

JavaScript 1.0

Syntax

onUnload="handlerText"

Parameters

handlerText

JavaScript code or a call to a JavaScript function.

Description

Use onUnload within either the BODY or the FRAMESET tag, for example, <BODY onUnload="...">.

In a frameset and frame relationship, an onUnload event within a frame (placed in the BODY tag) occurs before an onUnload event within the frameset (placed in the FRAMESET tag).

Event properties used

Property Description
type

Indicates the type of event.

target

Indicates the object to which the event was originally sent.

Examples

In the following example, onUnload calls the cleanUp function to perform some shutdown processing when the user exits a Web page:

<BODY onUnload="cleanUp()">

See also

onLoad

For general information on event handlers, see the Client-Side JavaScript Guide.

For information about the event object, see event.


Table of Contents | Previous | Next | Index

Last Updated: 05/28/99 12:01:01

Copyright (c) 1999 Netscape Communications Corporation