JavaScript
Random Image Display
by admin on Sep.23, 2009, under JavaScript, Random Image Display
Here I would like to share about “How could we display images randomly with the use of simple JavaScript“. I assume that you have basic knowledge of Jscript and know about the Arrays and Mathematical functions.
Here is the code of randomImage.js file,
function ev_random_img()
{
var myimages=new Array()
myimages[1]=”adv1.gif”
myimages[2]=”adv2.gif”
myimages[3]=”adv3.gif”
myimages[4]=”adv4.gif”
myimages[5]=”adv5.gif”var ry=Math.floor(Math.random()*myimages.length)
if(ry==0){ry=1;}
var imgpath =Â “images/” + myimages[ry];
document.getElementById(’imgadv’).src = imgpath;}
In the Above code I have defined an Array myimages and put the image name there, in second step I used Math.random to generate random numeric value and Math.floor fuction to round the value.
In Variable ‘imgpath’ I stored the complete path, as my images will be placed under ‘images’ folder that is why I made this string.
Finally by using getElementById method, I get the reference of the ‘image’ object with the specified ID. I have used ‘.src ‘ property to change the source path of image with the randomly generated path.
On the HTML page, just place
<script src=”script/ randomImage.js ” ></script>
At the head and put an image holder with ID ‘imgadv’.
<img src=”../” alt=”#” width=”348″ height=”203″ hspace=”10″ />
similarly If you want to change background style then follow all that same just a small change at the last
var bgpath =Â “url(images/adv/splats/” + bgimages[ry] + “)”;
document.getElementById(’splats’).style.backgroundImage = bgpath;
where ’splats’ is the ID given to the table or DIV at the HTML page. Variable ‘bgpath’ will have the complete string of path.
In Addition to above, add the lines below for random background image:
var bgimages = new Array()
bgimages[1] = “yellow-splats.gif”;
bgimages[2] = “aqua-splats.gif”;
bgimages[3] = “green-splats.gif”;
bgimages[4] = “blue-splats.gif”;
bgimages[5] = “purple-splats.gif”;
bgimages[6] = “pink-splats.gif”;var bgpath =Â “url(images/adv/splats/” + bgimages[ry] + “)”;
//document.getElementById(’splats’).style.backgroundImage = ‘url(images/adv/adv2.gif)’;
document.getElementById(’splats’).style.backgroundImage = bgpath;
