Java Reference
In-Depth Information
Displaying random Images with Object property Event handlers
and the Event Object
trY it out
In this Try It Out, you rewrite ch10_example1.html to use the Event object instead of this . Type in
the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 10: Example 2</title>
</head>
<body>
<img src="usa.gif" onclick="changeImg(event)" />
<img src="mexico.gif" onclick="changeImg(event)" />
<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];
}
</script>
</body>
</html>
Save the page as ch10_example2.html . Load the page into your browser, and you will see a page
similar to ch10_example1.html . Click an image, and you'll see it change to a random picture.
The code for this page is almost identical to ch10_example1.html . This new version just has a few
changes.
The first two changes are in the onclick event handlers of the <img/> elements. Instead of passing this
to changeImg() , you pass event .
The next change is in the changeImg() declaration:
function changeImg(e) {
The parameter name is now e , meaning event. Keep in mind that it doesn't matter what you call this
parameter, but the general convention is to use e .
Search WWH ::




Custom Search