Java Reference
In-Depth Information
<head>
<title>Chapter 10: Example 4</title>
</head>
<body>
<img id="img0" src="usa.gif" />
<img id="img1" src="mexico.gif" />
<script>
var myImages = [
"usa.gif",
"canada.gif",
"jamaica.gif",
"mexico.gif"
];
function changeImg(e) {
var el = e.target;
var newImgNumber = Math.round(Math.random() * 3);
while (el.src.indexOf(myImages[newImgNumber]) != -1) {
newImgNumber = Math.round(Math.random() * 3);
}
el.src = myImages[newImgNumber];
}
document.getElementById("img0").onclick = changeImg;
document.getElementById("img1").onclick = changeImg;
</script>
</body>
</html>
Save the page as
ch10_example4.html
. Load the page into your browser, and you will see a page
similar to
ch10_example2.html
. Click an image, and you'll see it change to a random picture.
The code for this page is almost identical to
ch10_example2.html
. The first changes are in the
<img>
tags. They no longer have
onclick
attributes, and they now have
id
attributes. The first image has an
id
of
img0
, and the second is
img1
. These elements have an
id
so that you can reference them in your
JavaScript code.
The only other changes are the final two lines of JavaScript code:
document.getElementById("img0").onclick = changeImg;
document.getElementById("img1").onclick = changeImg;
You use
document.getElementById()
to retrieve the two
img
objects from the DOM and assign their
onclick
properties, thus setting up the
changeImg()
functions to handle the
click
events on both
img
objects.
Removing an event handler is rather trivial. Simply assign
null
to the event handler property, like this:
img1.onclick = null;