Random Images by using simple to modify JavaScript

Websites become very easy boring when the images stay static. So on heavy used sites on the internet and intranet sites we can get arround the problem rather easy. The most simple solution is random images each time the user visits the page.

There are ofcourse a lot more advanced options as well like by using DHTML or databases. I will continue to talk about those in future tutorials. Now getting back to the simple but yet very usefull Random Images Java Script, we will get right to the core of the code and explain what you need to know:


<script language="JavaScript" type="text/javascript">
// This script was supplied by Dave Joosten
// For support and info go read the Tutorial at http://www.dmxzone.com/ShowDetail.asp?NewsId=5417|
var id = 3; // Total number of images
var ranimage = new Array(id); // Array to hold the filenames

ranimage[0] = "http://www.yourwebsite.com/graphic1.jpg";
ranimage[1] = "http://www.yourwebsite.com/graphic2.jpg";
ranimage[2] = "http://www.yourwebsite.com/graphic3.jpg";

function choseRandom(range) {
if (Math.random)
return Math.round(Math.random() * (range-1));
else {
var now = new Date();
return (now.getTime() / 1000) % range;
}
}
//
var choice = choseRandom(id);
</script>


Just copy the script above and modify it to your needs. Each time there are comments after the // that explain what it does.

In the sample code there are 3 images, defined in var id = 3 ; change this to the total number of images you wish to add in the script. Then you need to put the full list of images with one line per image in the following format ranimage[number starting with 0 then 1, etc..] = "imagename.format";

Then place this script below where you want the randomly selected graphics to show on your page. Change the width and height attributes to suit your graphics:

<script language="JavaScript">document.writeln('<td' + '><img src="' + ranimage[choice] + '" height="180" width="160" border="0" ><' + '/td>');</script>
 

If you have any questions, comments or problems, discuss them further in the forum for it by clicking on the *Discuss* graphic.

Have fun with it,

Dave Joosten

Comments

Be the first to write a comment

You must me logged in to write a comment.