spacer

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

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

Sr Instructional Designer D2L-Moodle,Clearance
WSI Nationwide, Inc.
US-NJ-Fort Monmouth

Justtechjobs.com Post A Job | Post A Resume
Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs


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]

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint

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

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