Ad-Rotation in JavaScript | 2 | WebReference

Ad-Rotation in JavaScript | 2

To page 1current page

Ad-Rotation in JavaScript

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 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 "" 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 = ["", "", ""], 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.

About the Author

Jonathan Fenocchi is a Web developer who primarily works in the fields of Web Design, client-side scripting, and PHP scripting. His web site is located at:

To page 1current page

Created: June 5, 2003
Revised: January 14, 2004