HTML and CSS Reference
In-Depth Information
Understanding Events and Event Handlers
An event is an action that occurs within a Web browser or Web document. Almost
every object in a Web page or browser is associated with several different events. For
example, one event associated with Web form buttons is the action of being clicked by
users. Another event occurs when a user hovers the mouse pointer over a button without
clicking it. A Web document itself is associated with events such as the action of being
loaded or unloaded by a browser.
With JavaScript you can attach a program to the occurrence of each event using an
event handler . Thus, you can have browsers run a script of your own whenever your
page is loaded or unloaded. There are several ways to attach event handlers to page and
browser objects. In this tutorial, you'll examine how to add an event handler to a page
element using an HTML attribute, as in the code
< element on event =” script ”> ...
where element is the name of the page element, event is the name of an event associ-
ated with that element, and script is a command or a collection of commands to be
run in response to the event. If you intend to run several commands in response to an
event, it's easiest to place them within a function and run the function using a single
command. One commonly used event handler is the onclick event handler, which runs
a program in response to a user clicking an element with the mouse button. For example,
the event handler in the following code runs the calcTotal() function when a user
clicks the Total Cost button:
<input type=”button” value=”Total Cost” onclick=”calcTotal()” />
Inserting an Event Handler as an HTML Attribute
• To insert an event handler as an HTML attribute, apply the HTML code
< element on event = “ script ”> ...
where element is the Web page element, event is the name of an event associated
with the element, and script is a command to be run in response to the event.
Figure 11-4 lists some other commonly used event handlers you can apply to objects
in the Web page and browser. You also can view an extended list of event handlers in
Appendix F.
Search WWH ::




Custom Search