Home > Articles > Open Source > Ajax & JavaScript

This chapter is from the book

Project III: Random Banner Ad Rotator Script

Word of your skills with JavaScript and images has spread to the marketing department, and they have tracked you down for a project that is near and dear to their hearts. Currently on the site, at the top of every secondary page, there is a little banner advertisement for one of the company's products that, if clicked, will take the user to the store section of the site (see Figure 2–5). The way it is set up now is that if they want to have different products showing up, they need to hardcode which product banner goes on a specific page. Because it's quite a hassle to keep track of multiple images and which page they show up on, up until now they have settled for having just a single product banner throughout the site. After seeing what you've done on the site, they're hoping that you can give them the ability to have multiple banners up on the site, so they can showcase a broader range of products. You've given it some thought and looked around on the Internet for similar functionality on other sites, and it looks as if you've come up with a good idea.

Figure 2-5FIGURE 2–5 Secondary page with product banner.


The plan is to set up a script that will not only randomly insert a different product banner on the page each time the page is loaded by a user, but rotate which banner is showing every 20 seconds while the user is on the page. So, if the marketing people want to showcase five different products, all they'll have to do is create the five graphics, drop them in a specified directory, and our script will randomly choose one of those five images to place on a given page. The first step is to find out the number of different banners the marketing department wants to have up on the site. After a quick call to marketing, you find out they indeed need five different product banners. Armed with that knowledge, it's time to get going on our script.

Creating and Inserting the Image Objects

Because this is a script that is going to be used on all pages of the site except the home page, it makes sense to put it into our external JavaScript file, so that's where we will be working for the most part in this project. Now, as in the other scripts that we've done that have worked with image replacement, we need to create some IMAGE objects, one for each product banner that we want available to our script. Let's start by creating the five IMAGE objects that we'll need. Unlike in our previous scripts, we don't have the graphics that we'll be actually using up on the site yet—the marketing folks are still trying to figure out which products to highlight. We've had one of the designers create five temporary graphics that we can use for now (see Figure 2–6).

Figure 2-6FIGURE 2–6 Temporary product banner images.

Because we don't know the names of the products that are going to be used and because marketing may want to occasionally change which products are showcased, we've named the graphics as follows:

product_banner_1.gif
product_banner_2.gif
product_banner_3.gif
product_banner_4.gif
product_banner_5.gif

This not only will make it easier to write our script, but it will make for less work later on when marketing wants to switch the products that they are showcasing. The reason for this will become clear when we get down to the function that will be running most of our script. But first, now that we have graphics to use in building our IMAGE objects, let's get that done. As we will be placing this script into our jsFunctions.js file, we'll place it right below our navigation rollover functions.

// Creating Image Objects for Product Banners
if (document.images) {
product1Banner=new Image(200, 56);
product1Banner.src="images/product_banners/product_banner_1.gif";

product2Banner=new Image(200, 56);
product2Banner.src="images/product_banners/product_banner_2.gif";

product3Banner=new Image(200, 56);
product3Banner.src="images/product_banners/product_banner_3.gif";

product4Banner=new Image(200, 56);
product4Banner.src="images/product_banners/product_banner_4.gif";

product5Banner=new Image(200, 56);
product5Banner.src="images/product_banners/product_banner_5.gif";
}
. . . 

We have created five IMAGE objects named in numeric order product1Banner through product5Banner, and we told the marketing department that the images they should use are in a subdirectory of the images directory called product_banners. This step should look pretty familiar, as we used it in the last two projects. Now that we have our IMAGE objects, let's move on the creation of the function that will run the script.

Random Image Generator Function

The first step we need to take in our script is to figure out which graphic will show up when the page first loads, because there are five images to choose from. We need to generate a random number between 1 and 5 that we can use to choose a graphic. Luckily for us, there is built-in functionality within JavaScript to do this. Let's get started on our first line.

The Math Object

To achieve the first part of our script, we need to use the built-in Math object of JavaScript. This object contains methods and properties that supply mathematical functions and values. For our purposes, we need the two methods Math.random() and Math.round(). First, we use the random method.

// First Generate a Random number that will be used to
// choose the initial product banner displayed on the page

var prodStart = Math.random()*4+1;
. . . 

Let's take a close look at what is going on here. On the left-hand side of the assignment operator, we have the by now familiar creation of a variable, which will hold the value of whatever is on the right-hand side of the operator. In this case, it's a variable name prodStart, which will end up holding a random number between 1 and 5. How we get the random number takes a little more explaining. The random method of the Math object returns a random number between 0 and 1, so what you end up with is a decimal between 0 and 1, like so:

0.5489732579249

You're probably wondering how we get from there to a number between 1 and 5, huh? Have no fear: Enter some of that math that you were sure you would never use once you got out of school. First, we multiply the decimal returned by the random method by 4; once this is done, we will have a decimal number somewhere between 0.0 and 4.0. Finally, we add a value of 1 to the current number so that we end up with a decimal number between 1.0 and 5.0, such as one of these:

1.2489732579249
3.4589378128
4.8628879248931138

For our purposes, however, we need a nice whole number, so we need to use another of the Math object's methods in the next line of our script.

// First Generate a Random number that will be used to
// choose the initial product banner displayed on the page

var prodStart = Math.random()*4+1;
prodStart = Math.round(prodStart);
. . . 

This line uses the round method of the Math object; it will round off any number that is placed inside of its parentheses. In our case, we have inserted the prodStart variable, which carries the number we got from the random method on the line above. The round method then returns a whole number between 1 and 5, which will then be restored into the prodStart variable. We will use this variable later on in another part of our script, which actually prints out the initial product banner. First, however, we need to create the function that will be called to change the banner randomly every 20 seconds once the page is loaded. We call the function bannerChanger(). Let's add the framework for our function directly after the lines above.

// First Generate a Random number that will be used to
// choose the intitial product banner displayed on the page

var prodStart = Math.random()*4+1;
prodStart = Math.round(prodStart);

// Next Create the function which will change the images
// once the page is loaded

function bannerChanger () {
	. . .
}

The first thing we need to do when our function is called is to again generate a random number between 1 and 5, so this first portion of our function will be almost identical to the first two lines of code in our script, with only one small change.

// First Generate a Random number that will be used to
// choose the initial product banner displayed on the page

var prodStart = Math.random()*4+1;
prodStart = Math.round(prodStart);

// Next Create the function which will change the images
// once the page is loaded

function bannerChanger () {
   prodStart = Math.random()*4+1;
   prodStart = Math.round(prodStart);
   . . .
}

The only difference in these first two lines is that we took out the new variable declaration (var) from the first line. Because we have already created this variable, there is no reason to do so again. Once these first two lines execute, when the function is called, we now have a new random number to use to display a new graphic. All we need to do now is tell the JavaScript engine which graphic to display.

// First Generate a Random number that will be used to 
// choose the initial product banner displayed on the page

var prodStart = Math.random()*4+1;
prodStart = Math.round(prodStart);

// Next Create the function which will change the images
// once the page is loaded

function bannerChanger () {
 prodStart = Math.random()*4+1;
 prodStart = Math.round(prodStart);
 document.images['addBanner'].src = eval("product" + prodStart +
"Banner.src");
 . . .
}

What we are doing in this new line of code should look pretty familiar. It's the same technique we've used in the first two projects in this chapter. We reset the source property of the image named prodBanner to one of the other five product banners, using the random number we have generated. The final step in creating our function is to make sure that this function will be called again in another 20 seconds to change the product banner once more. To do this, we use a built-in timer method called setTimeout(). The syntax of the setTimeout() method is as follows.

setTimeout(expression, msec)

Once called, setTimeout() waits the specified amount of time and then executes the expression that is given. In our case, we want it to wait 20 seconds and then call our bannerChanger() function again, so let's insert the setTimeout() method into our script.

// First Generate a Random number that will be used to
// choose the initial product banner displayed on the page

var prodStart = Math.random()*4+1;
prodStart = Math.round(prodStart);

// Next Create the function which will change the images
// once the page is loaded
function bannerChanger () {
   prodStart = Math.random()*4+1;
   prodStart = Math.round(prodStart);
   document.images['addBanner'].src = eval("product" + prodStart +
     "Banner.src");
   setTimeout("bannerChanger()", 20000);
}
. . .

We are now finished with our bannerChanger() function. There is just one last piece we have to add to this section of our script, then we will move down to the section of HTML where we want to print out our product banner graphic. We set it up so that once the bannerChanger() function has been called, it will keep re-calling itself every 20 seconds. However, we need to set it up so that the function gets called in the first place, so we need to add another setTimeout() method which will be executed upon the loading of the page. It will be identical to our first setTimeout(), located outside of the bannerChanger() function, like so.

// First Generate a Random number that will be used to 
// choose the intitial product banner displayed on the page

var prodStart = Math.random()*4+1;
prodStart = Math.round(prodStart);

// Next Create the function which will change the images
// once the page is loaded

function bannerChanger () {
   prodStart = Math.random()*4+1;
   prodStart = Math.round(prodStart);
   document.images['prodBanner'].src = eval("product" + prodStart +
        "Banner.src");
   setTimeout("bannerChanger()", 20000);
}

// Set timer to call the bannerChanger() function for the

// first time

setTimeout("bannerChanger()", 20000);

There. We're done with this section of our script; let's move to where we want to have the product banner printed out on our page.

Dynamically Printing Out the Image

Here is the section of HTML where the existing product banner is.

<table cellspacing="0" cellpadding="0" width="590">
   <tr>
      <td>
        <img src="images/secondary_top.gif" alt="Shelley Biotech"
          width="333" height="68" border="0"><a
          href="store/index.html"><img
          src="images/product_banners/product_banner.gif" alt=""
          width="204" height="68" border="0"></a><br> 

As you can see, it is currently just calling product_banner.gif. We need to add a script that will dynamically print out whichever product banner the initial random number generation specifies. We use a technique similar to the second project we did in Chapter 1. First, we take out the existing image and insert our <script> tags and our browser cloaking.

<table cellspacing="0" cellpadding="0" width="590">
   <tr>
      <td>
        <img src="images/secondary_top.gif" alt="Shelley Biotech"
         width="333" height="68"
          border="0"><a href="store/index.html">
<script language="JavaScript1.2">
<!-- cloak from non JavaScript capable browsers

. . .

// End cloaking from non JavaScript browsers -->
</script>
</a><br>

Next, we use the document.write() method to print out our random product banner graphic.

<table cellspacing="0" cellpadding="0" width="590">
   <tr>
     <td>
        <img src="images/secondary_top.gif" alt="Shelley Biotech"
         width="333" height="68"
         border="0"><a href="store/index.html">
<script language="JavaScript1.2">
<!-- cloak from non JavaScript capable browsers
document.write('<img src="images/product_banners/product_banner_'
  + prodStart + '.gif" width="204" height="68" alt="Buy Now"
  name="prodBanner">');

// End cloaking from non JavaScript browsers -->
</script>
</a><br>

Let's look at the document.write() line a little closer. We have it print out the first part of our image tag, specifying which directory to look in for our image as well as the first part of the image's name. Then we add to that the random number held in the prodStart variable, and finally finish the name of the graphic and the rest of its attributes, such as width, height, and name. So, if the variable prodStart is holding the value of 3, this is what will be printed out by the script:

<img src="images/product_banners/product_banner_3.gif" 
width="204" height="68" alt="Buy Now" 
name="prodBanner">

That about wraps it up for this project. We now have a script that randomly prints out a product banner graphic and every 20 seconds refreshes it with another random product banner.

Reviewing the Script

We introduced several new concepts during the creation of the script, so let's take one more look at what we did to create this script. First, we created the IMAGE objects and the function.

// Creating Image Objects for Product Banners
if (document.images) {
product1Banner=new Image(200, 56);
product1Banner.src="images/product_banners/product_banner_1.gif";

product2Banner=new Image(200, 56);
product2Banner.src="images/product_banners/product_banner_2.gif";

product3Banner=new Image(200, 56);
product3Banner.src="images/product_banners/product_banner_3.gif";

product4Banner=new Image(200, 56);
product4Banner.src="images/product_banners/product_banner_4.gif";

product5Banner=new Image(200, 56);
product5Banner.src="images/product_banners/product_banner_5.gif";
}
// Generate a Random number that will be used to choose the
// intitial product banner displayed on the page

var prodStart = Math.random()*4+1;
prodStart = Math.round(prodStart);

// Create the function which will change the images once
// the page is loaded

function bannerChanger () {
   prodStart = Math.random()*4+1;
   prodStart = Math.round(prodStart);
   document.images['prodBanner'].src = eval("product" + prodStart +
     "Banner.src");
   setTimeout("bannerChanger()", 20000);
}

// Set timer to call the bannerChanger() function for the
// first time

setTimeout("bannerChanger()", 20000);

Here are the steps we took to create this portion of the script:

  1. We created the five IMAGE objects that we needed for our product banners.

  2. We created a variable name prodStart and assigned it a random number between 1.0 and 5.0.

  3. We rounded off that number to a whole number between 1 and 5 and reassigned it to the variable prodStart. This variable holds the value of the graphic that will be displayed when the page is first loaded.

  4. We created a function called bannerChanger(), which updates the product banner graphic every 20 seconds.

  5. Inside of the function, we again generated a random number between 1 and 5 and assigned it to the prodStart variable.

  6. We used that value to change the source property of the prodBanner image on the page.

  7. We set a timer using the setTimeout() method to re-call the bannerChanger() function after 20 seconds.

  8. Once finished with the bannerChanger() function, we added one more timer to call the bannerChanger() function when the page first loads.

Next we moved over to the spot in the HTML where we want the product banner to be located.

<table cellspacing="0" cellpadding="0" width="590">
   <tr>
     <td>
        <img src="images/secondary_top.gif" alt="Shelley Biotech"
         width="333" height="68" border="0"><a
         href="store/index.html">
<script language="JavaScript1.2">
<!-- cloak from non JavaScript capable browsers

document.write('<img src="images/product_banners/product_banner_'
               + prodStart + '.gif" width="204" height="68"
               alt="Buy Now" name="prodBanner">');

// End cloaking from non JavaScript browsers -->
</script>
</a><br>
  1. We got rid of the existing product image <img> tag.

  2. We inserted our script framework into the HTML and cloaked for non-JavaScript-capable browsers.

  3. We used the document.write() method along with the value held in the prodStart variable to print out the random product banner graphic.

We have been introduced to several new aspects of JavaScript in this first script, including

  • The Math object along with its random and round methods.

  • The setTimeout() method.

Recap

You will find that image rollovers are by far the most commonly used JavaScript implemented on Web sites today. Almost every site you go to these days makes use of them in one way or another, so a good knowledge of how they work and what their limitations are can be a great asset to a programmer. Once you have the basics down, use that knowledge to experiment with different rollover techniques. You will be surprised at some of the creative and exciting rollovers you can devise.

Advanced Projects

  1. Use the onClick() event handler to create navigation images that change not only upon rollover but when the user clicks on the image as well.

  2. Create a page on which a random image replaces an existing image when the category images are rolled over.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020