1. Home
  2. Computing & Technology
  3. JavaScript

Cycling Banner

2. Obtain the Script

clr gif
More of this Feature

Introduction Add to Your Page

To make a cycling banner for your web page you need to copy the following script and attach it to the head section of your page.

var imgs = new Array(); var imgcnt = 0; var thisimg = 0;
imgs[imgcnt++] = 'graphics\/pic1a.gif';
imgs[imgcnt++] = 'graphics\/pic2a.gif';
imgs[imgcnt++] = 'graphics\/pic3a.gif';

function rotate() {
if (document.images) {
thisimg++;
if (thisimg >= imgcnt) thisimg = 0;
document.rollimg.src = imgs[thisimg];
setTimeout("rotate();",
5000);
}
}
setTimeout("rotate();",
10000);

The code shown in bold should be kept exactly as shown

In my example, I have three images so I need three sets of lines to define three images. You just need to specify as many separate entries as you need for your particular setup.

The one other thing you may want to change is the speed at which the images replace each other. The above code specifies 10000 (10 seconds) as the initial delay before the images start changing (so as to allow time for all of the images to load) and 5000 (5 seconds) for the delay between subsequent changes. You can specify whatever delay periods you want just remeber that the numbers are milliseconds.

Once you have created your code you just save it to an external javascript file. I called mine img1.js. You then link it into the head of your page using the following code:

<script type="text/javascript" src="img1.js">
</script>

Now all that remains is to add the images to your page.

Sample Page | Obtain the Script | Add to Your Page
Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.