Handling Events
As mentioned in Hour 1, not all scripts are located within <script> tags. You can also use scripts as event handlers. While this might sound like a complex programming term, it actually means exactly what it says: Event handlers are scripts that handle events.
In real life, an event is something that happens to you. For example, the things you write on your calendar are events: "Dentist appointment" or "Fred's Birthday." You also encounter unscheduled events in your life: for example, a traffic ticket, an IRS audit, or an unexpected visit from relatives.
Whether events are scheduled or unscheduled, you probably have normal ways of handling them. Your event handlers might include things like When Fred's birthday arrives, send him a present or When relatives visit unexpectedly, turn out the lights and pretend nobody's home.
Event handlers in JavaScript are similar: They tell the browser what to do when a certain event occurs. The events JavaScript deals with aren't as exciting as the ones you deal withthey include such events as When the mouse button clicks and When this page is finished loading. Nevertheless, they're a very useful part of JavaScript.
Many JavaScript events (such as mouse clicks) are caused by the user. Rather than doing things in a set order, your script can respond to the user's actions. Other events don't involve the user directlyfor example, an event is triggered when an HTML document finishes loading.
Event handlers are associated with particular browser objects, and you specify the event handler in the tag that defines the object. For example, images and text links have an event, onMouseOver, that happens when the mouse pointer moves over the object. Here is a typical HTML image tag with an event handler:
<img SRC="button.gif" onMouseOver="highlight();">
You specify the event handler as an attribute to the HTML tag and include the JavaScript statement to handle the event within the quotation marks. This is an ideal use for functions, since function names are short and to the point and can refer to a whole series of statements.
NOTE
You'll learn more about event handlers in Hour 10, "Responding to Events."