Random Banner Rotation Script

by Joe Gillespie — Feb 1, 2003

You may have noticed that some of my banners rotate - the one on the WPDFD home page is a prime example. Each time you load the page, you get a different ad. This is done with a little JavaScript routine which I will share with you.

There are two scripts. One in the body of page at the place you want the banner to appear and one in the head (or in an externally linked .js file if you prefer).

This main script sets up an array of banners, much like the array you would use for rollovers.

var max=3;
var thisBanner=1;
var banner=new MakeBannerArray(max);

function MakeBannerArray(n)
{
this.length=n;
for (var i=1; i<=n;i++)
{
this[i]="";
}
return this;
}

Every banner requires all the HTML to display that banner to be put into an array element. You should, of course, substitute your own link URL and the path to your image file in each instance. The easiest way to do this is to insert the actual banner on the page and copy and paste the HTML into the script inside single quotes.

banner[1]='<a href="--- link URL ---"><img src="--- path to image file ---" width="468" height="60" alt="whatever"><\/a>';
banner[2]='<a href="--- link URL ---"><img src="--- path to image file---" width="468" height="60" border="0" alt="whatever"><\/a>';
banner[3]='><a href="--- link URL ---"><img src="--- path to image file ---" width="468" height="60" alt="whatever"><\/a>';

Note that when HTML is put into JavaScript like this, you need to 'escape' certain special characters such as the slash in '/a'. This is done by putting a backslash in front of it - '\/a'. Depending on which syntax checker you use, it may also suggest that you encode some other characters as entities but I haven't found this necessary.

To generate the random number, I use this little routine which generates a random number between 1 and max.

function rand(n)
      {
      rnum=Math.floor(n*Math.random())+1;
      return rnum;
      }

Finally, the function that is called from the page and pulls it all together is just this:-

function setBanner()
      {
      thisBanner=rand(max);
      }

The script that goes on the page looks like this:-

<script type="text/javascript" language="JavaScript">
<!--
setBanner();
document.write (banner[thisBanner]);
// -->
</script>

The setBanner() function generates a random number and passes a random array element back to the document.write (banner[thisBanner]); statement which prints it to the page at the point where the script resides.

Del.icio.us Digg Technorati Blinklist Furl reddit Design Float