Home » Tutorials Advanced Tutorial

Automatic Ad-Rotation in JavaScript

1.9/5.0 (12 votes total)
Rate:

Jonathan Fenocchi
February 17, 2006


Jonathan Fenocchi
Jonathan Fenocchi is a talented young developer coming at you from southern TX, USA. Accessibility advocate, proficient programmer, and determined designer, Jonathan spends his free time researching new technologies, developing new ideas, playing video games and listening to rock music. Jonathan runs a Slightly Remarkable blog where he focuses on web-related content, and continues to pursue his goals as an aspiring web developer."

Jonathan Fenocchi has written 20 tutorials for JavaScriptSearch.
View all tutorials by Jonathan Fenocchi...

In a past column, I've written about how to display random advertisements when the page loads. To complement that past article, we're going to focus on an oft sought-after feature: automation. This article will focus on rotating the ads, in random order, over a period of time without reloading the page. I also address an issue brought up by the readership of my previous article, that of automatic ad rotating without reloading the page.

To begin, let's have a look at the code that was used in the previous column:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ad Rotation in JavaScript</title>
<script type="text/javascript"><!--
var returnValue = true;
var links = ["http://yahoo.com/", "http://msn.com/", "http://cnn.com/"];
var imgs = ["yahoo.gif", "msn.gif", "cnn.gif"];
var len = (links.length + imgs.length) / 2;

if((len*2)%2 == 1){returnValue=false;}

function showAd(){
   if(returnValue==false)
         {document.write('<img src="blank.gif" alt="">');return false;}
   var rand = Math.floor(len*Math.random())
   document.write("<a href=\""+links[rand]+"\" title=\"Go to "+links[rand]+"\"><img src=\""+imgs[rand]+"\" alt=\"Go to "+links[rand]+"\"></a>");
}
// --></script>
</head><body>
<script type="text/javascript"><!--
showAd();
//--></script>
<noscript> <img src="blank.gif" alt=""> </noscript>
</body></html>

Here, we’ll make a few modifications to the code, which has the effect of optimizing it. Here's the new code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ad Rotation in JavaScript</title>
<style type="text/css"><!--
   #myAd img {
      border: none;
   }
--></style>
<script type="text/javascript"><!--
var links = ["http://yahoo.com/", "http://msn.com/", "http://cnn.com/"]; // link addresses
var imgs = ["yahoo.gif", "msn.gif", "cnn.gif"]; // link images
var len = (links.length + imgs.length) / 2; // length

function showAd(){
   if(len%2 == 0){
             document.write('<img src="blank.gif" alt="">');
         return false;
      }
    var rand = Math.floor(len*Math.random());
    document.write('<a href="'+links[rand]+'" title="Go to '+links[rand]+'" id="myAd">');
   document.write('<img src="'+img[rand].src+'" alt="Go to '+links[rand]+'" name="myAdImg"></a>');
}
//--></script>
</head><body>
<script type="text/javascript"><!--
showAd();
//--></script>
<noscript><img src="blank.gif" alt=""></noscript>
</body></html>

There aren't a lot of differences, but you'll notice that I've added a STYLE tag below the TITLE tags. This will remove that bothersome 2-pixel, blue border from our image.

Note: For more information, you can read up on the CSS official specification: www.w3.org/TR/CSS2/.

Moving onward, we’ve removed the "returnValue" variable. Instead of having to add another variable, we did the length calculation inside of our showAd() function. This if statement simply divides "len" by two, then checks to see what the value is of the remainder. If it is zero, a blank image will be displayed to avoid JavaScript errors (remember, it's a fail-safe device). The last thing we've done is add an ID ("myAd") to the link, and a NAME ("myAdImg") to the image. This way, we can refer to the image and its containing link whenever we need to -- which will be set at an interval of your choice. Let's create the rest of the new code, then examine it further.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ad Rotation in JavaScript</title>
<style type="text/css"><!--
   #myAd img {
      border: none;
   }
--></style>
<script type="text/javascript"><!--
var links = ["http://yahoo.com/", "http://msn.com/", "http://cnn.com/"]; // link addresses
var imgs = ["yahoo.gif", "msn.gif", "cnn.gif"]; // link images
var img = []; // preloading array
var len = (links.length + imgs.length) / 2; // length
var timeBasis = 1; // in seconds

   // preload images
      for(i=0; i<imgs.length; i++){
         img[i] = new Image();
         img[i].src = imgs[i];
      }

function showAd(){
   if(len%2 == 0){
            document.write('<img src="blank.gif" alt="">');
         return false;
      }
   var rand = Math.floor(len*Math.random());
   document.write('<a href="'+links[rand]+'" title="Go to '+links[rand]+'" id="myAd">');
   document.write('<img src="'+img[rand].src+'" alt="Go to '+links[rand]+'" name="myAdImg"></a>');
   setInterval("updateAd()", timeBasis*1000);
}

function updateAd(){
   var r = Math.floor(len*Math.random());
      if(!document.links) return false;
         for(i=0; i<document.links.length; i++){
            if(document.links[i].id == "myAd"){
               if(document.links[i].href != links[r]){
                  document.links[i].href = links[r];
                  document.images['myAdImg'].src = img[r].src;
         } else {
               updateAd();
         }
       }
     }
}
//--></script>
</head><body>
<script type="text/javascript"><!--
showAd();
//--></script>
<noscript><img src="blank.gif" alt=""></noscript>
</body></html>

Quite a bit, isn't it? Let's check out the newest codes:

var img = []; // preloading array

This is an empty array, which holds preloaded images. This means that the advertisements will change instantly, instead of having to load first.

var timeBasis = 1; // in seconds

This is a variable which we will multiply by 1,000 to get x number of milliseconds for the setInterval function. I've set it to one second so that you can see how it works in the demonstration code. This time-basis determines when the next advertisement will appear in the place of your current ad.

   // preload images
      for(i=0; i<imgs.length; i++){
         img[i] = new Image();
         img[i].src = imgs[i];
      }

Remember that "img" array? This is where we're using it. The for loop runs through the SRC's of all of your images, and loads them for you before the document loads. Since the images are preloaded, there will be no delay between the ad rotations.

   document.write('<a href="'+links[rand]+'" title="Go to '+links[rand]+'" id="myAd">');
   document.write('<img src="'+img[rand].src+'" alt="Go to '+links[rand]+'" name="myAdImg"></a>');
   window.onload = function(){setInterval("updateAd()", timeBasis*1000)};

This script is not entirely "new," but there are some key changes that make it work. You'll notice we're not using the "imgs" array; we're using our preloaded images. It’s important to recall that we’ve added an ID and NAME to the A and IMG tags, as well. In order for the script to be easier to read, I've split the document.write statements into two lines. The last line here is crucial: when the document loads, we create a function to call setInterval. This tells JavaScript to run the function updateAd() one time every X milliseconds. In this case, X is the timeBasis variable times 1,000. We multiply this by 1,000 in order to get the millisecond-equivalent to the number in timeBasis. This way, we can put the number of seconds in the variable, and not have to update the milliseconds in the variable each time.

function updateAd(){
   var r = Math.floor(len*Math.random());
      if(!document.links) return false;
         for(i=0; i<document.links.length; i++){
            if(document.links[i].id == "myAd"){
               if(document.links[i].href != links[r]){
                   document.links[i].href = links[r];
                   document.images['myAdImg'].src = img[r].src;
            } else {
                   updateAd();
            }
          }
       }
}

The updateAd function, finally. Let's dissect this thing. Here, we set a variable, "r," to a random number below the length variable. This represents the index of the link and its corresponding image. Next, we check to see if the current version of JavaScript has the "document.links" array. This array contains all the links on the page -- including the ones generated by JavaScript. Obviously, this function won't work if the document doesn't know what the array is. After we're sure that the array exists, we run a for loop. We run through all of the links on the page until we find the one with the "myAd" ID. Then, we make certain that the current random link is not equal to the past one -- if it is, the ad won't update, because it will be the same. In the event that it is, the function becomes recursive. This means that we call the function inside of itself. It’s recalculated with the intention that the random number will not be the same. In most cases that won’t happen. Finally, we update the link with the ID "myAd" and the image with the name "myAdImg."

Remember to keep the NOSCRIPT tags (this prevents users who don’t have JavaScript from seeing anything). You will, obviously, need a "blank.gif" image of some sort. I recommend that this script be included in a common JavaScript file, so that you only have to update one file for all of the JavaScript pages to update. It will also save you a lot of file space and bandwidth.

Conclusion

This article has explained how to create advertisements in JavaScript, load them in random order and automatically update them using a time interval without reloading the page. This technique should prove useful to those of you who have high-traffic Web sites and require ads that fit into your layout.


Add commentAdd comment (Comments: 0)  

Advertisement

Partners

Related Resources

Other Resources

arrow