- Project I: Image Rollover Script
- Project II: Multiple Image Rollover Script
- Project III: Random Banner Ad Rotator Script
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 25). 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 25 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 yetthe 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 26).
FIGURE 26 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:
We created the five IMAGE objects that we needed for our product banners.
We created a variable name prodStart and assigned it a random number between 1.0 and 5.0.
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.
We created a function called bannerChanger(), which updates the product banner graphic every 20 seconds.
Inside of the function, we again generated a random number between 1 and 5 and assigned it to the prodStart variable.
We used that value to change the source property of the prodBanner image on the page.
We set a timer using the setTimeout() method to re-call the bannerChanger() function after 20 seconds.
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>
We got rid of the existing product image <img> tag.
We inserted our script framework into the HTML and cloaked for non-JavaScript-capable browsers.
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
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.
Create a page on which a random image replaces an existing image when the category images are rolled over.