|
Random Images with JavaScript |

|
|
This is the second part of my collection "Simplest Possible JavaScripts". All these pages result from things I wanted to do and then did do. I'm taking what I learned and trying to provide examples that are as simple as possible. I am not a programmer. Everything I know about JavaScript, I've taught myself, using information available on the web. If you'd like to make use of that information too, I've put links to all of it on my JavaScript Links page. |
|
|
How It Works |
|
When the page containing this script is loaded, it displays an image picked at random from an array of image names. |
||
|
Setting up an Array |
||
|
|
JavaScript can store more than one piece of information in a variable. This works sort of like an itemized list. This sort of multi-part variable is called an array. Each piece of information in an array is assigned a reference, in this script I've assigned a number to each entry, but words could be used instead. As always, create the script inside of the <SCRIPT> section of the <HEAD> of the HTML document. The first thing I did was to initialize the array eith the root name ImageList : ImageList = new Array() The contents of the array immediately follow that line: ImageList[1]="pbar-analysis.gif" The bracketed numbers after the array name represent the index of that array entry, I'll be using that number to call the images later. This array uses the complete name of the GIF file instead of an image object like the rollover script. I made this descision for simplicity's sake. This script just displays a random image from the array when the document is loaded. |
|
|
Random Numbers |
||
|
To pick the image to display, the script needs a random number. Thankfully, the JavaScript's creators added a random command the the language with version 1.1. The command to generate a random number looks like this: Math.random() Of course, this is a pseudo-random number, true random numbers are more complex. If that bother's you (it doesn't bother me), there are true-random functions available from some of the JavaScript repositories. Unless you are doing extensive testing and recording, you'll probably never know the difference. This is for web pages, not astro-physics. The number returned is a decimal between 0 (zero) and 1 (one). They look like this: That isn't actually as useless as it might look, but you'll have to do some math to get what you want. If you wanted a random number from zero to ten, just multiply that decimal number by 10 and parse the result--oh, maybe now would be a good time to mention the parseInt() function. |
||
|
parseInt() - Make integers from decimals |
||
|
This built in JavaScript function rounds decimal numbers to the nearest integer. This line returns the integer 3: parseInt(3.14) Just in case high school algebra occupied the first set of brain cells you sacrificed to time; an integer is a number without any decimals. |
||
|
Pick a number from 1 to 10 |
||
|
To make JavaScript pick a number from any given range, you need to tell the script to do some simple math. Here is the code that tells JavaScript to pick a number from one to ten: (Math.random() * 9) + 1 Here's what happened: First, Math.random() generates a random number from zero to one, just like the above example. Next, the random number is multiplied by 9. The reason the script multiplies by 9 instead of 10 is because computers start counting from 0 (zero) instead of 1. There are ten digits between 0 and 9, just like between 1 and 10. Now there is a random number between zero and nine. Just ass 1to get a number between 1 and 10. View this number. All that decimal stuff was there to make a point. parseInt() will remove the decimals and return a clean integer. The following code does everything the previous example did, except the last thing it does is hack off the decimals. View the number now. parseInt((Math.random() * 9) + 1) Next the script needs to use that random number to choose an image from the array. |
||
|
Setting up a function |
||
|
Efficient scripts use functions to help eliminate redundancy. Usually a function is just a named chunk of code that can be activated, or repeatedly activated, with only one command. This script, has only one function. The function ImagePicker() picks a random number that decides which image to load. The parentheses are sometimes used to send data to a function, I'll probably discuss that in a future example. The complete function, ImagePicker(), looks like this:
function ImagePicker(){
pic=parseInt((Math.random()*(ImageList.length-1))+1);
return pic;
}
The first line of the function declares that whatever is inside the following brackets "{}" will be executed whenever the name ImagePicker() is called. The second line assigns a random number, picked with the methods described above, to the variable pic. The last line tells JavaScript to return the value represented by pic. Then the closing bracket ends the function.
|
||
|
Using entity values to create the Image tag |
||
|
Any attribute of an HTML tag can be replaced with a JavaScript entity. The syntax for JS entities is the very siimilar to standard HTML entities. In HTML, an entity object, usually higher ASCII characters, are coded between a & (ampersand) and a closing ; (semicolon). To dependably get a © (copyright symbol), type © to get an & (ampersand), type &. JavaScript uses this &...; container too, except it replaces the character name with a bracketed JavaScript command. This entity will place a random number anywhere it's placed into a document's HTML:
&{ImagePicker()};
From there, it's easy to format the name of the array:
&{ImageList[ImagePicker()]};
The random number function fills in the number's space between the array brackets. It's the same as typing ImageList[7] , except that the computer chooses the number. Because the entity is basicaly a variable, what the computer actually gets is the complete name of an image, as was entered into the ImageList array. Replacingthe image SRC= value will produce a complete image tag with a randomized source. The final tag looks like this:
<IMG SRC="&{ImageList[ImagePicker()]};" WIDTH=100 HEIGHT=200>
|
||
|
The actual code |
||
|
That explanation was much longer than the actual code. The following is the complete code for simple document that will load a random image everytime the page loads. Don't believe me? Try it . Here's the code:
<HTML>
<HEAD>
<TITLE>
Doubter's page
</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide from none JavaScript Browsers
Image1= new Image(121,153)
Image1.src = "joe_open.jpg"
Image2 = new Image(121,153)
Image2.src = "joe_blink.jpg"
function SwapOut() {
document.Rupert.src = Image2.src; return true;
}
function SwapBack() {
document.Rupert.src = Image1.src; return true;
}
// - stop hiding -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<CENTER>
<P>
<A HREF="http://www.joemaller.com/"
onmouseover="SwapOut()"
onmouseout="SwapBack()">
<IMG NAME="Rupert"
SRC="joe_open.jpg"
WIDTH=121
HEIGHT=153
BORDER=0>
</A>
</P>
If you use this, please give me credit.
</CENTER>
</BODY>
</HTML>
|
||
|
This example uses : |
||
|
This example uses images that are convenently the same size. If you wanted to use images of varying sizes, just include the height and width attributes in each array entry: ImageList[1]='"pbar-analysis.gif" height="20" width="50"' Just be sure to modify your image tag to accomodate those quotes. That is a workaround I came up with to simplify this script. This script starts the array at [1] instead of [0] . This is because JavaScript counts the zero's place in the array, even if it isn't there. Actually, it will fill in any missing numbers. If you made an array whose only element was [99] , array.length would still return 99. But by starting the array at [1] , and then simply subtracting one from the array.length command I managed to avoid all of that. Adding 1 before parsing serves two functions: First, it makes the number parsable. Without adding 1, the number returned was sometimes NaN (Not a Number). I guess that's because the number to be parsed was 0 (zero), and for some reason, zero cannot be parsed into an integer. Second, adding 1 adjusts the value returned to match the number of elements in the array, since that |
||
|
Feedback |
||
|
Please let me know if this page helped you or if the code is in use somewhere. If you have any problems or suggestions, please write. |
||