January 1, 2000 - Attribute-Based Event Handlers
January 1, 2000 Attribute-Based Event Handlers Tips: January 2000
Yehuda Shiran, Ph.D.
|
<HTML>
<HEAD>
<TITLE>Hello / Goodbye</TITLE>
</HEAD>
<BODY onLoad="alert('Hello')" onUnload="alert('Goodbye')">
</BODY>
</HTML>
A page built with this HTML 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 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: