Home » Tutorials Beginner Tutorial

Ad-Rotation in JavaScript

2.3/5.0 (15 votes total)

Jonathan Fenocchi
February 17, 2006

Jonathan Fenocchi
Jonathan Fenocchi is a talented young developer coming at you from southern TX, USA. Accessibility advocate, proficient programmer, and determined designer, Jonathan spends his free time researching new technologies, developing new ideas, playing video games and listening to rock music. Jonathan runs a Slightly Remarkable blog where he focuses on web-related content, and continues to pursue his goals as an aspiring web developer."

Jonathan Fenocchi has written 20 tutorials for JavaScriptSearch.
View all tutorials by Jonathan Fenocchi...

Ad-rotation is widespread and important for many sites, such as those that offer free services. With Ad-rotation, it’s important that your ads display properly, be easy to read, to understand and be interesting, but you don’t want the ads to annoy visitors and cause them to leave your site (which would result in loss of potential funds through advertisements). In this article, you'll learn how to generate random advertisements in JavaScript, and explore some other features along the way.

So Where Do We Start?

Since HTML is the basis for the Web, we'll go ahead and create a simple HTML page, to which you can add or replace code as necessary.

<html lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ad Rotation in JavaScript</title>
<script type="text/javascript"><!--
// --></script>
<!-- HTML Code -->


Now, let's start creating our script. We're going to use document.write() to write the HTML to the page, so that users who don't have JavaScript enabled won't see the ad. This means we'll need to use the <noscript> </noscript> tags to insert an image where the ad would be if the user had JavaScript. Let's set up an array of links and corresponding images...

<script type="text/javascript"><!--
var links = new Array("http://yahoo.com/", "http://msn.com/", "http://cnn.com/");

/* The variable "links" is an array containing three strings (listed above). */

var imgs = new Array("yahoo.gif", "msn.gif", "cnn.gif");

/* The variable "imgs" is an array of images that MUST correspond with those in the "links" array. This way, yahoo.gif will be displayed when the link goes to http://yahoo.com/, msn.gif will be displayed when the link goes to http://msn.com/ and so on. */

As explained in the comments above, the first array contains three strings. We can shorten that a bit by using this:

var links = ["http://yahoo.com/","http://msn.com/","http://cnn.com/"];

We can refer to the first string as follows:


This will alert, "http://yahoo.com/" in an alert box. Arrays begin at zero-index, so above there are three strings but you refer to them as links[0] ("http://yahoo.com"), links[1] ("http://msn.com/"), and links[2] ("http://cnn.com/"). The same applies with our imgs array.

Now let's get down to determining validation. Now what happens if you accidentally have an error in your script, say by some server-side script, and it doesn't display an image? Chances are, your page will look pretty mangled. To prevent that, we'll make sure that an image is displayed, in this case a blank one...

var len = (links.length + imgs.length) / 2;

/* Get the length of the amount of strings of both arrays and split it in half. In this case, the result will be three. */

if((len*2)%2 == 1)
/* If the length of both arrays added together is an odd number, we have a boo-boo... Set returnValue to false. */

Here, we have the variable len, which is short for "length," and it adds both the lengths of the arrays together; then divides them by two. The result should always be even, if it isn't, we have a problem--the images and links won't correspond. The solution is to display the blank image. When we call our function to write the HTML to the page, we check the value of the global variable, returnValue. But before we go any further, we have to initialize the global variable returnValue before anything else in the script. This is what we have so far...

<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)


Now then, let's review. First, we initialized the global variable, returnValue, and set its Boolean value to that of true. The variable is global because we defined it outside of a function. If we had started out with a function, the variable would not be global; it would be specific to that function only. Next, we initialized two arrays: links and imgs. These two arrays correspond with each other to display the right image and link on the page, rather than the wrong ones.

Next, we initialize the variable len, and set it to the length of both variables added together, and divided by two. We'll use this variable later on in our showAd() function. After that, we run an if/else statement, which basically checks if it is an even or odd number. We multiply len by two to get the total of both variable lengths (remember we divided len by two earlier), and then we use the modulus operator to get the remainder of the division of len and two. In other words, we divide len by two (len/2) and then get the remainder of that equation--the result is what the modulus operator provides. (For more information on the modulus and other Mathematical operators, see http://devedge.netscape.com/.../ops.html#1042400.) If the returned value is 1, the number is odd. So assuming that our script is missing an array value, the returnValue would be set to equal false.

To continue, we want to write out the function that will display the ad. Remember, creating a function and calling a function are two different things--we're putting this part of the code in the HEAD tag, but we're going to call it from another part of the page, so that the image loads as if it had been placed there statically (no pre-loading, in other words).

function showAd()
{ /* Begin function showAd() */

/* If we set the return value to false, use document.write() to display a blank image, and then exit the function (don't display the ad) */
{document.write('<img src="blank.gif">'); return false;}

var rand = Math.floor(len*Math.random());
/* Calculate a random number from zero to the maximum possible number, which we earlier set to the variable "len." */

var link = links[rand];
/* Set the variable "link" to point to one value of the "links" array. Since "rand" is a random number, in this case from 0 to 2, it will select one of the three strings in the "links" array. Remember again, arrays begin at index zero. So the first value of the links array is links[0], which would give us the value "http://yahoo.com/" and the second would be links[1]. The total string amount is three, but we're going from 0 to 2, which would select properly from the array index. */
var img = imgs[rand];
/* We're doing the same thing with the imgs array here, as we did with the links array above. How will it correspond with the first array, though? Simple, we set the variable "rand" to a random value, but it does not change every time we call it. This means that if rand were to equal 1 in links[rand], it will also equal 1 in img[rand] and continue to equal 1 until it was set to something else. */

document.write("<a href=\""+link+"\" title=\"Go to "+link+"\"><img src=\""+img+"\" alt=\"Go to "+link+"\"></a>");

/* Use document.write() to write out the HTML code. Here basically all we're doing is filling in the HREF, TITLE, SRC and ALT attributes with different variables that we set above. You can test this by using alert(link) or alert(img) before or after the above line, but not before the variables link and img are set. */

} // And finally, we end the function

Here, we check to see if we set returnValue to false, and if so, display a blank image when the function is called to avoid any broken images or page display failures. Then we use return false to exit the function before anything else in the function is run--this ends the function in the case of a syntax error. Next a variable (rand) is set to a random number whose maximum value is equal to the variable len. Remember, len is equal to the length of both arrays, divided by two. The result is what's necessary to specify how far the random value can go. In this case, its maximum is 2.

Next, we set the variable img to the random string, and we set the variable link to the random string; it corresponds properly because the variable rand doesn’t change each time we call it--it only changes when we change it. After all the processing is done, it's time to write the HTML to the page and use the variables link and img as the values. Now we need to call the function. In your HTML code, use the following script and it will display your random image wherever it’s placed--you can even call it more than once (but a different ad may be displayed, depending on the value of rand).

<script type="text/javascript"><!--
<img src="blank.gif" alt="">

Shortening the Code

More? Yep… We can shorten this as seen below:

<html lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ad Rotation in JavaScript</title>
<script type="text/javascript"><!--
var returnValue = true, links = ["http://yahoo.com/", "http://msn.com/", "http://cnn.com/"], imgs = ["yahoo.gif", "msn.gif", "cnn.gif"], len = (links.length + imgs.length) / 2;

if((len*2)%2 == 1){returnValue=false;}

function showAd(){
{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>
<script type="text/javascript"><!--
<noscript> <img src="blank.gif" alt=""> </noscript>

Here is working example of Ad-Rotation in practice. Clicking on the link repeatedly, randomly rotates the ads.

Why not just change the SRC of the image onLoad?

The reason we don’t do that, is because all users with JavaScript enabled would have to download the new ad after the page loads—which would just take up more processing time and bandwidth. This method will display a different image for users without JavaScript (a blank image), and users that have JavaScript will see a different ad in the order of where it would be had you used static HTML code instead. This avoids the page loading problems, and reduces confusion.

Add commentAdd comment (Comments: 0)  



Related Resources

Other Resources