How It Works 20
The first line in the script block at the top of the page defines a variable with page-level scope. This is an array that contains your list of image sources.
var mylmages = new Array("usa.gif","canada.gif","jamaica.gif","mexico.gif");
Next you have the changelmg() function, which will be connected to the onclick event handler of an <IMG> tag surrounding each of your images. 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. You pass this function one parameter — the index in the images array of the img object related to that click event—so that you know which image you need to act on.
In the first line of the function, you use the passed parameter to declare a new variable that points to the img object in the images[] array corresponding to the image that was clicked, as follows:
function changelmg(imgNumber) {
var imgClicked = document.images[imgNumber];
Following this, you set the newlmgNumber variable to a random integer between 0 and 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 converted to an integer (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 mylmages array.
var newImgNumber = Math.round(Math.random() * 3);
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 property of the current image, you know it's the same and that you need to get another random number. You keep looping until you get a new image, at which point myImages[newImgNumber] will not be found in the existing src and -1 will be returned by the indexOf() method, breaking out of the loop.
while (imgClicked.src.indexOf(myImages[newImgNumber]) != -1) {
newImgNumber = Math.round(Math.random() * 3);
Finally, you set the src property of the img object to the new value contained in your myImages array. You return false to stop the link from trying to navigate to another page; remember that the HTML link is only there to provide a means of capturing an onclick event handler.
imgClicked.src = myImages[newImgNumber]; return false;
Next you connect the onclick event of the first <IMG> tag to the changeImg() function:
<img name=img0 src="usa.gif" border="0" onclick="return changeImg(0)">
And now to the second <IMG> tag:
<img name="img1" src="mexico.gif" border="0" onclick="return changeImg(1)">
Passing 1 in the changeImg() function lets the function know that image 1, the second image in the page, needs to be changed.
Post a comment