spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / jf / column6 / 1 current pageTo page 2
[next]

UNIX System Administrator - SUN Solaris, Veritas, EMC, Shell Scripting, SAN (NYC)
Next Step Systems
US-NY-New York

Justtechjobs.com Post A Job | Post A Resume
Developer News
ActiveState Debuts Open Source Business Suite
Salesforce Offers Visual App Builder
Codesion Steps Out From CVS's Shadow


Automatic Ad-Rotation in JavaScript

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>


home / programming / javascript / jf / column6 / 1 current pageTo page 2
[next]


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Use Web Caching to Make Your Web Site Faster · Creating an Online Shopping Cart Mechanism in PHP · Log JavaScript Errors Using an AJAX-driven Web Service
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Configuring Granular Settings for a Database Level Audit · The Perils of a Web 2.0 Transition on Your Business Processes · Facebook Redesigns Site —Again — Nears 400M Mark

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

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