|
January 1, 2000 Attribute-Based Event Handlers Tips: January 2000
Yehuda Shiran, Ph.D.
|
|
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:
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:
It's also possible to include several statements in one event handler script by delimiting the statements with semicolons. Here's an example:
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:
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:
Many HTML tags support event handlers. In the previous examples we used the tag's
The output of the preceding code is:
People who read this tip also read these tips: Look for similar tips by subject: |