You are here : Home - Web Development - Javascript - Banner Rotation
Javascript Banner Rotation
This is not a full blown banner ad management tracking system - it has its use though for smaller sites who want to place a few affiliate or internal banners on their site.
basically it has 4 parts
1: a random number generator
2: the image source
3: the link
4: the target window
The script below refreshes the banner every 5 seconds, you can set your own value.
if you don't want the banners to rotate on the page but you want a random banner each time page loads all you have to do is remove the linesetTimeout("get_img();",r_delay); from the get_img()
function.
see the script in action
<script language="JavaScript" type="text/javascript">
<!--
var min_num = 1;
var max_num = 5;
var diff = max_num-min_num+1 ;
var rnd_number=1;
//the refresh delay in seconds
var r_delay = 5;
//one for each image
var banner_image = new Array(5);
banner_image[1]="1.gif";
banner_image[2]="2.gif";
banner_image[3]="3.gif";
banner_image[4]="4.gif";
banner_image[5]="5.gif";
//one for each image
var banner_link = new Array(5);
banner_link[1]="http://www.webdevtips.co.uk";
banner_link[2]="http://www.webdevtips.co.uk";
banner_link[3]="http://www.webdevtips.co.uk";
banner_link[4]="http://www.webdevtips.co.uk";
banner_link[5]="http://www.webdevtips.co.uk";
//one for each image leave as "" for current window
var banner_target = new Array(5);
banner_target[1]="";
banner_target[2]="new";
banner_target[3]="new";
banner_target[4]="new";
banner_target[5]="new";
r_delay=r_delay*1000;
function get_img(){
rnd_number=Math.floor(Math.random()*diff + min_num);
eval("document.images.the_banner.src=banner_image[" + rnd_number + "]");
//remove this line if you only want the banner rotated at load
setTimeout("get_img();",r_delay);
}
function go_url(){
if(banner_target[rnd_number] == ""){targetwin="_top";}
else
{targetwin=banner_target[rnd_number];}
eval("window.open(url = banner_link[" + rnd_number + "],'"+ targetwin +"');");
}
// -->
</script>
You also need to add to the body tag
<body onload="get_img();">
You use this code to place the image and link
<a href="#" onClick="go_url();return false;"><img src="1.gif" width="20" height="20" alt="" border="0" name="the_banner"></a>
Tip : Set a default link on the anchor tag and your preferred default image as the img src. This means that if a visitor arrives with javascript disabled you still have an active ad link.
tested on:
Windows IE6, Netscape 4.5, Netscape 6, Opera 6, Mozilla 1
Linux Netscape 4.7, Netscape 6, Opera 6, Mozilla 1, Konqueror