
Random Images in Javascript
Alright guys and gals, this one is simple. It's a wonder more artist sites don't use this sort of script. As soon as I get the time I know I'll be implementing it a little better on my site as well. Think of it, you could really jazz up your gallery page with a nice splash image that's different almost everytime the user visits! Things don't get quite as boring as fast, and people are encouraged to come back... especially if you change the whole array of pictures to a whole whack load a new ones.
In order to create this script you'll need:
1. A bunch of images that your script will be able to select from
2. An IMG tag with a name in your body that currently only contains a transparent GIF as the SRC
3
. Understanding of HTML and Basic Javascript
What's going to happen here is that you're basically going to store all of your images in an array, and then you're going to tell the Javascript to call a random item from that array and replace your transparent GIF with said file. Easy as pie, eh?
So, we make an array with the images in it, and then we make a function that choose an image from that array, and then we call that function in the body tag, like so:
<script language="javascript">
<!--
//This is your array for your pictures
thePictures = new Array("images/rand1.jpg", "images/rand2.jpg", "images/rand3.jpg", "images/rand4.jpg", "images/rand5.jpg", "images/rand6.jpg", "images/rand7.jpg", "images/rand8.jpg", "images/rand9.jpg")
//This basically counts how many pictures there are
imageCount = thePictures.length
function choosePicture()
{
if (document.images)
{
//choose a random number
randomNumber = Math.floor((Math.random() * imageCount))
//the random number determines which item in the array to display
document.randomPicture.src = thePictures[randomNumber]
}
}
</script>
</head>
<body onload="choosePicture()">
<img src="images/spacer.gif" alt="Random Image" name="randomPicture" width="20" height="10" />
And you know what? That's all the code there is! To the left you can see an example of the script in action. I have mine basically choosing a random colored JPG from 9 different choices. Try refreshing the page, and you'll probably get another color... Unles it RANDOMLY chooses the same one again! Huh?! Huh!! I dunno... I thought it was pretty cool.
So, make sure you have your array of images, your function that creates a random number and uses it to select one of the choices from your array, and an event handler in your body tag that calls the function to start when the page loads. Don't forget that you have to use the same name that you used for your image as in your Javascript (I use the name "randomPicture" for mine).
And here's another way to copy the code:
Feel free to use those scripts, and credit me for the copy and paste too! I hope that all made sense.
This concludes the Javascript Random Image tutorial.
-Spence