The Navigator Event Model: Traditional Event Handlers - Doc JavaScript | WebReference

The Navigator Event Model: Traditional Event Handlers - Doc JavaScript


Traditional Event Handlers

The simplest way to catch an event is the traditional event handler, which was first implemented in Navigator 2.0x and Internet Explorer 3.0x. Simply specify the desired event handler as an attribute of its HTML tag. The following HTML document demonstrates the use of two event handlers in one tag:

<HTML>
<HEAD>
<TITLE>Hello / Goodbye</TITLE>
</HEAD>
<BODY onLoad="alert('Hello')" onUnload="alert('Goodbye')">
</BODY>
</HTML>

This page displays the message "Hello" when you load it, and "Goodbye" when you unload it. Notice that each event handler is a distinct attribute. An event handler script is executed when the corresponding event occurs. In this example, each event handler specifies a single statement:

alert('...');

It's also possible to include several statements in one event handler script by delimiting the statements with semicolons. Here's an example:

<HTML>
<HEAD>
<TITLE>Hello</TITLE>
</HEAD>
<BODY onLoad="alert('Hello'); alert('How are you?')">
</BODY>
</HTML>

As in any other script, you do not need a semicolon after the last statement. In fact, if you place each statement on a separate line, you don't need semicolons at all:

<HTML>
<HEAD>
<TITLE>Hello</TITLE>
</HEAD>
<BODY onLoad="alert('Hello')
              alert('How are you?')">
</BODY>
</HTML>

Event handlers are case-insensitive. For example, you can use ONLOAD, onLoad, or onload for the same purpose. As you can see, the event handler requires quotation marks to delimit the specified JavaScript code from the surrounding HTML content. JavaScript requires alternation of single and double quotation marks, so it is sometimes very annoying to have a full-size script in an event handler. Event handlers accept any script, as long as it's valid. For that reason, you should normally associate functions with event handlers, so the only statement you need in the event handler script is a function call:

<HTML>
<HEAD>
<TITLE>Hello</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function welcome() {
  alert("Hello");
}
// -->
</SCRIPT>
</HEAD>
<BODY onLoad="welcome()">
</BODY>
</HTML>

Many HTML tags support event handlers. In the previous examples we used the <BODY> tag's onLoad and onUnload event handlers. The following example shows how to use the onClick event handler with a simple button:

<SCRIPT LANGUAGE="JavaScript">
<!--
function clicked() {
  alert("You clicked a button.");
}
// -->
</SCRIPT>
<FORM>
<INPUT TYPE="button" VALUE="click here" onClick="clicked()">
</FORM>

The output of the preceding code is:

http://www.internet.com


Created: December 16, 1997
Revised: December 16, 1997

URL: http://www.webreference.com/js/column9/eventhandlers.html