spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / jf / 1 To page 1current page
[previous]

Senior JAVA Programmer
I T Search
US-MI-Lansing

Justtechjobs.com Post A Job | Post A Resume
Developer News
Sir Tim Talks Up Linked Open Data Movement
From L.A. to Vegas With 100GbE
Salesforce Rolls Out Big Summer '08 Update

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 http://devedge.netscape.com/library/manuals/2000/javascript/1.3/reference/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(returnValue==false)
/* 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"><!--
showAd();
//--></script>
<noscript>
<img src="blank.gif" alt="">
</noscript>


Shortening the Code

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


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<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(){
if(returnValue==false)
{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>
</head><body>
<script type="text/javascript"><!--
showAd();
//--></script>
<noscript> <img src="blank.gif" alt=""> </noscript>
</body></html>

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: http://cmm.sonoracabinets.com/

home / programming / javascript / jf / 1 To page 1current page
[previous]



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM eBook: Planning a Service Oriented Architecture
IBM eBook: Choosing the Right Architecture--What It Means for You and Your Business
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Avaya Article: Using Intelligent Presence to Create Smarter Business Applications
Intel Go Parallel Article: Getting Started with TBB on Windows
Microsoft Article: 7.0, Microsoft's Lucky Version?
Avaya Article: How to Feed Data into the Avaya Event Processor
IBM Article: Developing a Software Policy for Your Organization
Microsoft Article: Managing Virtual Machines with Microsoft System Center
Intel Go Parallel Article: Intel Threading Tools and OpenMP
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Silverlight 2 App and Walkthrough: Leverage Silverlight 2 with SQL Server and XML
IBM Article: Enterprise Search--Do You Know What's Out There?
HP Demo: StorageWorks EVA4400
Microsoft Article: The Progress and Promise of Deep Zoom
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
webref The latest from WebReference.com Browse >
Book Review: Head First JavaScript · Web Hosting Control Panels · Use Your Blog for Fast Search Engine Rankings
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
NetApp's Virtual Storage Strategy Crystallizes · F/MC Watch: A Cisco-Centric Approach · Olympic Time Trials Use Wi-Fi Mesh

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

URL: http://webreference.com/programming/javascript/jf/1