Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

494 LESSON 17: Introducing JavaScript


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
the attributes can be any JavaScript code, even multiple statements, separated by semico-
lons. Here’s an example that uses the onclick attribute on a link:
<a href="http://google.com/" onclick="alert(this.href); return false;">Google</a>
In this example, the value of the onclick attribute contains two statements. The first uses
the built-in alert() function to display the value in the href attribute of the link. The sec-
ond prevents the link from taking the user to a new page. So clicking the link will display
the alert message in Figure 17.7 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.

FIGURE 17.7
A JavaScript alert
message.

The Meaning of this
You might be a bit puzzled by the use of this as a variable name in an event han-
dler. Here, this is shorthand for the current object. When you’re using an event
handler in a tag, this refers to the object represented by that tag. In the previous
example, it refers to the link that the user clicked on. The advantage of using this
is that it places the event in a useful context. I could use the same attribute value
with any link and the code would still work as expected. It’s particularly useful when
you’re using functions as event handlers and you want to make them easy to reuse.
Free download pdf