Java Reference
In-Depth Information
The fi rst method of connecting code to events is easier, so why would you ever want to use the second?
Perhaps the most common situation in which you would want to do this is one in which you want to
capture an event for which there is no HTML element to write your event handler as an attribute. It is
also useful if you want the code attached to an event handler to be changed dynamically.
Try It Out Displaying a Random Image when the Page Loads
Let's look at another example in which you connect to a hyperlink's click event to randomly change the
image loaded in a page.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 6: Example 5</title>
<script type=”text/javascript”>
var myImages = new Array(“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];
return false;
}
</script>
</head>
<body>
<img name=”img0” src=”usa.gif” border=”0”
onclick=”return changeImg(this)“ />
<img name=”img1” src=”mexico.gif” border=”0”
onclick=”return changeImg(this)“ />
</body>
</html>
Save the page as ch6_examp5.htm . Again, you will need four image fi les for the example, which you
can create or retrieve from the code download available with this topic.
Load the page into your browser. You should see a page like that shown in Figure 6-3.
If you click an image, you'll see it change to a different image, which is selected randomly.
Search WWH ::




Custom Search