Java Reference
In-Depth Information
Figure 6-3
The fi rst line in the script block at the top of the page defi nes a variable with page-level scope. This is an
array that contains your list of image sources.
var myImages = new Array(“usa.gif”,”canada.gif”,”jamaica.gif”,”mexico.gif”);
Next you have the changeImg() function, which will be connected to the onclick event handler of the
<img/> elements defi ned in the page. You are using the same function for both images' onclick event
handlers and indeed can connect one function to as many event handlers as you like. This function
accepts one parameter called that. It is called that because you pass the this keyword to the function
which gives you immediate access to the img object you click. You can actually name the parameter
whatever you want, but most developers use the word “that” when it references this.
In the fi rst line of the function, you set the newImgNumber variable to a random integer between 0 and 3 :
function changeImg(that)
{
var newImgNumber = Math.round(Math.random() * 3);
The Math.random() method provides a random number between 0 and 1, and you multiply that by
three to get a number between 0 and 3. This number is rounded to the nearest whole number (0, 1, 2, or
3) by means of Math.round(). This integer will provide the index for the image src that you will
select from the myImages array.
The next lines are a while loop, the purpose of which is to ensure that you don't select the same image
as the current one. If the string contained in myImages[newImgNumber] is found inside the src prop-
erty of the current image, you know it's the same and that you need to get another random number. You
Search WWH ::




Custom Search