JS Random Images Script

A random image helps keep your page looking fresh for returning users instead of the same static image everytime.  The following is the code used to create a random images on a website everytime the page is refreshed. This is an exmple of JS code that you WOULD put between the HEAD tags. The <body> JS code (where you want to call the action) goes right where you want the images to appear.  It's really easy. You can use as many images as you want (in mine you can see I chose 6).  A link to the working model of this code is at: http://www.jdotnet.net/Creations.  All you need to do is keep refreshing the page and you'll see the images in the header change out each time.  Hope this helps some of you and have fun programming!

<HTML>
<head>
<Title> Page Title Here</Title>

<SCRIPT language="JavaScript">

<!-- Begin JS Script -->

<!-- Begin
// Set up the image files to be used.
var theImages = new Array() // do not change this
// To add more image files, continue with the
// pattern below, adding to the array.

theImages[0] = 'http://www.dl.utoledo.edu/images/header1.jpg'
theImages[1] = 'http://www.dl.utoledo.edu/images/header2.jpg'
theImages[2] = 'http://www.dl.utoledo.edu/images/header3.jpg'
theImages[3] = 'http://www.dl.utoledo.edu/images/header4.jpg'
theImages[4] = 'http://www.dl.utoledo.edu/images/header5.jpg'
theImages[5] = 'http://www.dl.utoledo.edu/images/header14.jpg'
theImages[6] = 'http://www.dl.utoledo.edu/images/header15.jpg'

// do not edit anything below this line

var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
   preBuffer[i] = new Image()
   preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write('<img src="'+theImages[whichImage]+'">');
}

//  End -->
</script>
</head>

<!--In the body where you want the random images to appear-->

<body>

<SCRIPT language="JavaScript">
<!-- Begin
showImage();
//  End -->
</script>

</body>
</HTML>

Comments

Excellent Instructions

December 12, 2003 by Sue Schmidt

You provided an excellent description of how to use and place this code!  Thanks for your thoroughness.  It will be extremely easy to implement.

Sue
Learning Technology Trainer

Why use so much code?

December 18, 2003 by Rick Speer

I find this code (below) works in my browser just as well. Is there some reason you have put the loop in there that I'm not familiar with?

// do not edit anything below this line

var p = theImages.length;
var i = Math.round(Math.random()*(p-1));

function showImage(){
document.write('<img src="'+theImages[i]+'">');
}

What' wrong with this picture?

February 21, 2008 by student 101

That code as it is, does work, THANK YOU!
I can make it loop through a folder using ASP or PHP.

Very simple really, did one here yesterday for that KW image thingy. http://www.jtechsystems.co.za/views.php?newsid=16/

The same rules apply here.
Enjoy...

You must me logged in to write a comment.