Java Reference
In-Depth Information
Now you'll find that you just get a message, and no attempt is made to go to
somepage.html
.
Note
Not all objects and their events make use of the return value, so
sometimes it's redundant.
Some events are not directly linked with the user's actions as such. For example, the
window
object has the
load
event, which fires when a page is loaded, and the
unload
event, which fires
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()">
Displaying random Images with htML attribute Event handlers
trY it out
In this Try It Out, you connect to an image's click event to randomly change the image loaded in a
page. Open your editor and type in the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 10: Example 1</title>
</head>
<body>
<img src="usa.gif" onclick="changeImg(this)" />
<img src="mexico.gif" onclick="changeImg(this)" />
<script>
var myImages = [
"usa.gif",
"canada.gif",
"jamaica.gif",
"mexico.gif"
];
function changeImg(that) {
var newImgNumber = Math.round(Math.random() * 3);
while (that.src.indexOf(myImages[newImgNumber]) != -1) {
newImgNumber = Math.round(Math.random() * 3);
}
that.src = myImages[newImgNumber];
}
</script>
</body>
</html>