Random image with javascript

Author: Mattias (mattias@999tutorials.com)
Categories: General www, Javascript
 Show a random image with the help of javascript. Only create the images and copy paste the script.
The tutorial:

Digg this, Post to del.icio.us,

It's very important that your web site is "alive" and it looks like something is happening.

One simple thing you can use to give your visitors something new is show them a random image every time they reload your page. There are number of times a function like this can be useful.

For example, change the image thing into quotes or tips if you like a function like that. Maybe show different sales pitches every time the page is reload. The places to use it is pretty many, just change the script a little.

 The script is pretty simple, you don't have to understand everything if you only want to use it for the function.

To get it working, enter your image names where image1.gif, image2.gif etc is written. Remove the rows you don't need anymore or add new ones. Just remember to increase the number if you add more.
You have to update the variable "numberOfImages" to match the number of images you have in the array.

How does it work, simple explanation

There is one function that takes one parameter. The parameter is the number of different results that the randomizer should return.
We have one array that holds the name of all your images. Add or remove  rows if you need. The variable randomNumber is set to a random number via the function.

The last row writes the actual html code that needs to show the image. (Remember to upload the images in the same directory, or change the image array)

Here is the script, just copy paste and start using it. You can put it somewhere after your body tag. 


<script language="JavaScript" type="text/javascript">
<!--
// Function that return a number between 0 and "nums - 1"
function getRandom(nums)
{
    var ranNum= Math.round(Math.random()*nums);
    return ranNum;
}

// Tells us how many images we have available.
var numberOfImages    = 5;
var randomNumber        = getRandom(numberOfImages);

// Create an array to hold the names of all images.
var image = new Array(numberOfImages);
image[0]="image1.gif";
image[1]="image2.gif";
image[2]="image3.gif";  
image[3]="image4.gif";
image[4]="image5.gif";

// Write the img tag with a random image name.
document.write("<img xsrc='" + image[randomNumber] + "' />");

--></script>



Digg this, Post to del.icio.us,
 


eXTReMe Tracker