Java Reference
In-Depth Information
Displaying random Images with Standard Event handlers
trY it out
In this Try It Out, you rewrite ch10_example4.html to use the standard DOM event model. Type in the
following code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 10: Example 6</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").addEventListener("click", changeImg);
document.getElementById("img1").addEventListener("click", changeImg);
</script>
</body>
</html>
Save the page as ch10_example6.html . Load the page into your browser, and you will see the familiar
page from the previous examples. Click an image, and you'll see it change to a random picture.
The only changes from ch10_example4.html are the final two lines of JavaScript:
document.getElementById("img0").addEventListener("click", changeImg);
document.getElementById("img1").addEventListener("click", changeImg);
Instead of using each element object's onclick property, you register the click event handler using
addEventListener() .
 
Search WWH ::




Custom Search