Automatic Ad-Rotation in JavaScript | 2 | WebReference

Automatic Ad-Rotation in JavaScript | 2

To page 1current page
[previous]

Automatic Ad-Rotation in JavaScript

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.

To page 1current page
[previous]

Created: June 5, 2003
Revised: November 3, 2004

URL: http://webreference.com/programming/javascript/jf/column6/1