JavaScript
Random Popups
Notes from the ZDU JavaScript workshop.
Creating a set of popups where the images swap randomly instead of in a pre-determined pattern.
Watch the buttons change as you pass your mouse over them.
How it works
Take a look at the source code for this page. The images are pre-loaded as usual. On MouseOver, instead of a predetermined image replacing the original image, an image is selected at random from an array, by invoking the javascript function "swapimage()" with the number of the image to replaced (the_image_name). For example, the code for the leftmost image is:
<a href="#" onMouseOver="swapImage('one');">
<img src="images/SquarePurple01.gif" name="one" border="0">
The javascript function "swapimage()" is given an array of images to choose from:
var number_array = new Array("SquarePurple01","SquarePurple02","SquarePurple03","SquarePurple04","SquarePurple05","SquarePurple06");
The code for the function is below. The first line works out the full name of the image (for example, window.document.one). The second line calcualtes the length of the array (6, as there is a list of 6 images), subtracts one (arrays are numbered from zero, so in this case the elements are numbered 0 to 5), uses a random number generator to generate a number between 0 and 5, then rounds that number to a whole integer. The result is the index (in the integer range 0 to 5) denoting which element of the array is going to be used time. Let's say it is 4. The third line concatenates "images/" + the selected element of the array (= number_array[the_index] = number_array[4] = "SquarePurple05" in my example), plus ".gif". This gives "images/SquarePurple05.gif" in this case. Line 4 assigns "images/SquarePurple05.gif" to the img source, thereby replacing the current image with a random new one.
The code on this page was inspired by a tutorial by Dave Thau on WebMonkey.
function swapImage (the_image_name)
{
var the_image = eval("window.document." + the_image_name); // line 1
var the_index = Math.round(Math.random()*(number_array.length-1)); // line 2
var the_new_image = "images/" + number_array[the_index] + ".gif"; // line 3
the_image.src = the_new_image; // line 4
}






