HTML and CSS Reference
<li><a href=”http://google.com/”> Google </a></li>
<li><a href=”http://www.nytimes.com/”> New York Times </a></li>
This page contains a script tag in the header, and that script tag contains a single function
declaration. The function, linkModifier() , changes the href attribute of all the links on
a reference to an array of all the links in the document. It iterates over each of those
links, changing their href properties from the values specified in the HTML to the new
URL. The main point of this example, though, is the onload attribute in the body tag,
which contains the call to linkModifier() . It's important to associate that call with the
onload event so that all the links on the page have been processed before the function is
called. If I'd put the function call inside the <script> tag, the function call might have
occurred before the page was loaded.
Most often, when using attributes to bind events, function calls are used, but the value of
colons. Here's an example that uses the onclick attribute on a link:
<a href=”http://google.com/” onclick=”alert(this.href); return
In this example, the value of the onclick attribute contains two statements. The first uses
the build in alert() function to display the value in the href attribute of the link. The
second prevents link from taking the user to a new page. So clicking the link will display
the alert message in Figure 14.4 and do nothing after the user acknowledges the alert.
Whether you're writing code in your event binding attribute or writing a function
that will be used as an event handler, returning false will prevent the default browser
action for that event. In this case, it prevents the browser from following the link. If the
onsubmit action for a form returns false, the form will not be submitted.