HTML and CSS Reference
In-Depth Information
Calling JavaScript Functions Using Event Handlers
Now that you have added user-defined functions to count down to a certain date, changed
the scroll bar color, used a drop-down menu, and added the date last modified at the
bottom of the page, you need to add code that calls these functions when the Web page is
loaded. JavaScript has two basic methods to call functions. One method to call a function
is to use event handlers and object methods. The other method is to code the function
name in a JavaScript section at the logical point of execution. The user-defined functions
written in this chapter execute using event handlers.
As you have learned, an event is the result of an action, such as a mouse click or a
window loading. An event handler is a way to associate that action with a function. For
example, when a user clicks a button or a check box, a JavaScript user-defined function
may be associated with that event. The associated function will execute if the event is
captured and then triggers, or calls, the JavaScript user-defined function. The general
form of an event handler is shown in Table 9-29.
Table 9-29 Event Handlers
General form:
<tag attribute eventhandler=“JavaScript code”>
where tag is the HTML tag; attribute is a property of the tag that can have a value assigned to it,
eventhandler is the name of the JavaScript event handler, and JavaScript code is the instruction to
execute, usually in the form of a function name
<body onLoad=“scrollColor()”>
JavaScript event handlers make Web pages more dynamic and interactive by allow-
ing JavaScript code to execute only in response to a user action, such as a mouse click
or selection of an item in a list. For a complete list of event handlers, see the JavaScript
Quick Reference in Appendix G. You use the onLoad and onChange event handlers in the
Midwest Bridal Expo Web page.
To have a JavaScript user-defined function execute automatically when a page loads,
use the onLoad event. The onLoad event handler triggers the associated function when
the Web page has completed loading into the browser. The onChange event handler
triggers when the value of an object changes. For example, when the user selects a list
item in the select list, the value of the select list is changed.
To Associate User-Defined Functions with the OnLoad Event
The following steps enter JavaScript code to associate the countDown(), scrollColor(), and copyRight() user-
defined functions with the onLoad event.
Click to the right of
the y in the <body>
tag in line 78, as
shown in Figure 9-14.
insertion point in <body> tag;
press SPACEBAR once to begin
adding onLoad event handler
Figure 9-14
Search WWH ::

Custom Search