Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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