Rotating A Banner On Schedule Via JavaScript / DOM

Recently asked on Yahoo! Answers:

On my website, I want to have a banner box that slowly rotates through 8 or so pictures automatically…?

No mouseover needed, the pictures will slowly swap on their own. I know this is a JavaScript, but don’t know the proper name for this function. Can anyone give me some guidance? All I need is the name of the function, I can look it up from there.

Thanks!!!!

This question should sound somewhat familiar to readers of this blog: We’ve dealt with displaying images based on the current time, randomly displaying an image, displaying an image based on user input and, earlier today, loading images, in order, every time a page is refreshed.

This question, therefore, wouldn’t seem that new. Except that we’re presented with two new challenges: We need not only retain what image to display next, we need to associate a URL with our image, too — so that people can click on the banner and go someplace.

As always, I have a working demo and downloadable code at the end of this discussion.

Step 1: Write The XHTML

Our XHTML for this exercise is simple:

  • An onload event for the body tag that points to our function, which we will call rotateBanner()
  • An anchor (hyperlink) with a unique ID, which we will call theLink;
  • An image with a unique ID, which we will call theBanner.
<body onload="rotateBanner()">
	<a id="theLink"><img id="theBanner" /></a>
</body>

Step 2: Create A Banner Class Constructor

Because we need to associate both the name of the image and the URL we want to link to that image, it makes sense for us to create a constructor for a new class we will call Banner.

The Banner class will have three properties: the name of the image; a caption we can display for the image; and the URL to which we want the image linked. Then, for each banner we want to display, we’ll create a Banner object and populate its properties with information unique to that banner.

function Banner(name, caption, url) {
	this.name = name;
	this.caption = caption;
	this.url = url;
}

Step 3: Declare Global Variables

Because our script is going to run on a timeout, it’s convenient for us to store certain variables as globals. The benefit of a global variable is that all functions and classes on the page can access its value; as a result, we can set its value from within the rotateBanner() function, and retain its value because it isn’t contained within the rotateBanner() function.

For more about how variable scope works, read this blog entry.

The two globals we’ll set are theInterval, which is the number of milliseconds (thousandths of a second) between banner refreshes; and theIndex, which records for us which banner we’re currently displaying.

var theInterval = 10000;
var theIndex = 0;

Step 4: Write The rotateBanner() Function

On to the main function. We first set some variables:

  • The HTTP path to the images, relative to the page that has this script;
  • A reference to the IMG tag that will contain our banner; and
  • A reference to the anchor that will contain our link.
function rotateBanner() {
	var theDirectory = "images/";
	var theImg = document.getElementById('theBanner');
	var theAnchor = document.getElementById('theLink');

Next, we declare an array that will hold all of our Banner objects: each array cell will create a new Banner, with the appropriate information passed as arguments to the constructor we made earlier.

var myImages = new Array();
myImages[0] = new Banner("000579822.jpg", "Christina Aguilera is smoking hot.", "http://www.yahoo.com");
myImages[1] = new Banner("000579823.jpg", "A slightly different angle on the previous shot.", "http://www.msn.com");
myImages[2] = new Banner("000579824.jpg", "These images come from a New Year's party of some sort.", "http://www.mtv.com/#/music/artist/aguilera_christina/artist.jhtml");
myImages[3] = new Banner("000579825.jpg", "Looks like Christina wants to get away from this photographer.", "http://www.google.com");
myImages[4] = new Banner("000579826.jpg", "And here's Christina Aguilera at the red carpet.", "http://www.dole.com");
myImages[5] = new Banner("000579827.jpg", "Christina Aguilera standing next to a couch, looking sultry.", "http://www.whitehouse.gov");
myImages[6] = new Banner("000579829.jpg", "And again, signalling her man, \"Let's get the Hell out of here.\"", "http://www.nfl.com");
myImages[7] = new Banner("000579830.jpg", "One last pose for the cameras ...", "http://www.curiousgeorge.com");
myImages[8] = new Banner("000579831.jpg", "... and Christina gives us a parting butt shot, which is very kind of her.", "http://www.christina-a.com");

With that done, we can go ahead and set the IMG and anchor tags to use the values for the current Banner object:

var thePath = theDirectory + myImages[theIndex].name;
theImg.src = thePath;
theImg.alt = myImages[theIndex].caption;
theImg.title = myImages[theIndex].caption;
theAnchor.href = myImages[theIndex].url;

With the current Banner set for use on the page, we increment theIndex by one.

We then check to see if theIndex is greater than the total number of Banner objects we have to display. If it is, we reset theIndex to 0, and start iterating through the Banner objects anew.

theIndex++;
if(theIndex > (myImages.length - 1)) {
	theIndex = 0;
}

For the final part of this function, we set the timeout of the script to be however long theInterval is, so that the Banner objects will rotate for us.

setTimeout('rotateBanner()', theInterval);

And that’s all there is to it. You can see a working demo here:

http://www.dougv.com/demo/js_rotating_image/

You can download this script and its related images from here:

Rotating A Banner On Schedule Via JavaScript / DOM Demo Code

I distribute code under the latest version of the Creative Commons Attribution / Share-Alike License.

Share This »
  • Digg
  • Yahoo! Buzz
  • Technorati
  • del.icio.us
  • Propeller
  • StumbleUpon
  • Reddit
  • Mixx
  • Twitter / Twit This
  • Pownce
  • Fark
  • Slashdot
  • NewsVine
  • BlinkList
  • Netvouz
  • Furl
  • Mister Wong
  • DZone
  • Ma.gnolia
  • Simpy
  • blogmarks
  • Blue Dot
  • Spurl
  • Sphinn
  • DotNetKicks
  • MySpace
  • Facebook
  • LinkedIn
  • Google Bookmarks
  • Yahoo! MyWeb
  • Windows Live Favorites

One Comment

  1. f1avor_f1av:

    Still writing great code i see. Have a good one, tc

Leave a comment