Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Web
Expertise: Intermediate
Jun 30, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Building a Rotating Banner Ad with JavaScript

Banner ads are common on any commercial site these days. But most of them use mechanisms like Server Push, Serve-side objects, or even services of third parties to rotate the banner. Here is a simple, inexpensive, JavaScript-based, implementation of a banner ad. This banner rotator shows a different gif image on each hit of the page and also rotates the images every two minutes.

<script language="JavaScript">
var timerID=0;
// image array - this array could be filled from the server side it it's
likely to have a variable number of images

var imgArray = new Array("banner1", "banner2", "banner3", "banner4",

function setupAdbanner() {
	timerID = setInterval("rotateBanner()", 2 * 60000);

function cleanupPage() {
	if (timerID)

function rotateBanner() {
imgIndex = Math.ceil(Math.random() * imgArray.length) - 1;
"images/" + imgArray[imgIndex] + ".gif";
  • The setupAdbanner() function needs to be called on loading (onload event) the page and the cleanupPage() function has to be called while unloading (unload event)
  • There should be an <IMG> tag declaration (assumes name="mainBanner" in this example) that is the place holder for the banner on the HTML page.
  • imgArray can be filled from the server side to add any number of images or to load image sets depending on the session.
Ajith Prasad
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date