Java Reference
In-Depth Information
<a href=”somepage.htm” name=”linkSomePage”
onclick=”return linkSomePage_onclick()”>
Click Me
</a>
</body>
</html>
Within the script block, you have created a standard function, and given it a descriptive name to help
you when reading the code. Here we're using ObjectName_event() as the function name. That way you
can instantly see what object on the page this relates to and which event is being connected to. So, in the
preceding example, the function is called linkSomePage_onclick() , because you are referring to
the onclick event handler for the a object with name linkSomePage . Note that this naming conven-
tion is simply something created by your authors; it's not compulsory, and you can use whatever
convention you prefer as long as you are consistent.
The onclick attribute is now connected to some code that calls the function linkSomePage_onclick() .
Therefore, when the user clicks the hyperlink, this function will be executed.
You'll also see that the function returns a value, true in this case. Also, where you defi ne your onclick
attribute, you return the return value of the function by using the return statement before the function
name. Why do this?
The value returned by onclick=”return linkSomePage_onclick()” is used by JavaScript to decide
whether the normal action of the link — that is, going to a new page — should occur. If you return true ,
the action continues, and you go to somepage.htm . If you return false , the normal chain of events (that
is, going to somepage.htm ) does not happen. You say that the action associated with the event is canceled.
Try changing the function to this:
function linkSomePage_onclick()
{
alert(“This link is going nowhere”);
return false;
}
Now you'll fi nd that you just get a message, and no attempt is made to go to somepage.htm .
Not all objects and their events make use of the return value, so sometimes it's redundant. Also, it's not
always the case that returning false cancels the action. For reasons of browser history rather than logic,
it's sometimes true that cancels the action. Generally speaking, it's best to return true and deal with the
exceptions as you fi nd them.
Some events are not directly linked with the user's actions as such. For example, the window object has
the load event, which fi res when a page is loaded, and the unload event, which fi res when the page is
unloaded (that is, when the user either closes the browser or moves to another page).
Event handlers for the window object actually go inside the opening <body> tag. For example, to add an
event handler for the load and unload events, you'd write the following:
<body onload=”myOnLoadfunction()”
onunload=”myOnUnloadFunction()”>
Search WWH ::




Custom Search