Home > Articles > Open Source > Ajax & JavaScript

This chapter is from the book

Project II: Multiple Image Rollover Script

It's that time of the year when the company puts out its annual report. This year the public relations department wants to make it available online. Most of it has already been posted, but there is one section that they could use a little help on. In the section of the report that deals with the sales figures, there is a set of graphs that compares sales over the last three years. The public relations department would like it if users could compare the charts for adjoining years. In other words, they want to be able to compare 1998 to 1999, and 1999 to 2000, and finally 2000 to 2001. After seeing the magic you've worked with the navigation rollovers, they wonder if you can set up this functionality with JavaScript rollovers instead of just laying out all of the graph comparisons in a huge page.

After some research and a little tinkering around with one of the designers, you think you have a way to give them what they are looking for, so you show them what you've worked out. Figure 2–3 shows what the page would look like before the user rolls over one of the year sets. Figure 2–4 shows what would happen if the user rolls over 2000–2001. They love the idea and tell you to get started on it.

Figure 2-3FIGURE 2–3 Shelley Biotech annual report page.


Figure 2-4FIGURE 2–4 Annual report page—with a year set highlighted.


First, let's look at the HTML for the section of the page that we are concerned with.

<tr>

   <td valign="top" align="left">
     <br><br><img
src="images/sales_comp_left_default.gif" alt="" width="162"
height="87" border="0"></td>

   <td valign="top" align="center">
     <font class="blkBldText">Year to Year Sales
Comparison</font><br>
      <br>
      <a href=" " class="blueLink">2000 - 2001</a><br>
      <br>
      <a href=" " class="blueLink">1999 - 2000</a><br>
      <br>
      <a href=" " class="blueLink">1998 - 1999</a></td>
   <td vlaign="top" align="left">
      <br><br><img src="images/sales_comp_right_default.gif"
alt="" width="162" height="87" border="0"></td>
</tr>

The designer on the project has gone ahead and created some temporary images for us to use until they get the final chart graphics done. In the existing HTML, you will notice that there are two images that we will have to switch out when the user rolls over a set of years: sales_comp_left_default.gif and sales_comp_right_default.gif. At the moment, the image that goes on the left has instructions for the user, while the image on the right is a plain white image. When a user rolls over a set of years, the image on the left will change to a chart of the first year in the set, while the image on the right will change to a chart of the second year in the set. Luckily, this is fairly similar to what we did in the previous project, so we'll be able to use the functions we wrote for the navigation rollovers as a starting point for our func

tions here. But first we need to create the image objects we will need for the project.

Creating and Inserting the Image Objects

As stated above, the designer has created temporary chart graphics for each of the four years we need to use in our comparisons. They are called:

sales_1998.gif
sales_1999.gif
sales_2000.gif
sales_2001.gif

To use them in our script, we need to create an IMAGE object for each of them. Because this script will be used only on this page, there is no need to put our script into an external JavaScript file, so let's insert it into the <head> of the HTML page.

<head>
<script Language="JavaScript1.2">
<!-- Code after this will be ignored by older browsers

// Creating Image Objects for Rollovers
if (document.images) {
sales2001=new Image(162, 87);
sales2001.src="images/sales_2001.gif";

sales2000=new Image(162, 87);
sales2000.src="images/sales_2000.gif";

sales1999=new Image(162, 87);
sales1999.src="images/sales_1999.gif";

sales1998=new Image(162, 87);
sales1998.src="images/sales_1998.gif";
}

  . . .
// -->
</script>

Just as in our previous project, we've inserted the script tag, cloaked the script from older browsers, and created the IMAGE objects that we'll need for our script.

Now that we have all of the IMAGE objects that we will need, let's go on to the next step of our script—modifying the rollover functions.

Inserting the Rollover Functions

Let's take a look at the functions we are using for our navigation rollovers. First, the On function will replace the image of the category name that the user rolls over with a highlighted image. Then the Off function changes the image back to the default version once the user rolls off of it. What's different in our current project is that we need the script to swap out not one but two images each time the On function is called; likewise, when the user rolls off of a set of years, the Off function needs to turn both of the changed images back to the default versions that show up when the page is loaded. To get started, let's copy the On and Off functions from the jsFunctions.js file and paste them underneath our new IMAGE objects.

<head>
<script Language="JavaScript1.2">
<!-- Code after this will be ignored by older browsers

// Creating Image Objects for Rollovers
if (document.images) {
sales2001=new Image(162, 87);
sales2001.src="images/sales_2001.gif";

sales2000=new Image(162, 87);
sales2000.src="images/sales_2000.gif";

sales1999=new Image(162, 87);
sales1999.src="images/sales_1999.gif";

sales1998=new Image(162, 87);
sales1998.src="images/sales_1998.gif";
}


// function to turn on rolled over graphic
function on(pic) {
   if (document.images) {
      document.images[pic].src=eval(pic + "On.src");
   }
}

// function to turn off rolled over graphic
function off(pic) {
   if(document.images) {
     document.images[pic].src= eval(pic + "Off.src");
   }
}

The first thing we need to do is change JavaScript comments and the names of the functions so that they don't conflict with the functions that control the navigation rollover functions. Let's call these new functions salesOn and salesOff.

// function to turn on sales comparison charts
function salesOn(pic) {
   if (document.images) {
      document.images[pic].src=eval(pic + "On.src");
   }
}

// function to turn off sales comparison charts
function salesOff(pic) {
   if(document.images) {
     document.images[pic].src= eval(pic + "Off.src");
   }
}

Now, let's make the changes to the salesOn function. Because we need this function to change two graphics, we need to create two variables to accept values passed in from the event handlers: one for the name of the image to be swapped out for the left-hand image and one for the name of the image that will show up on the right-hand side. Let's call these variables salesPic1 and salesPic2. These will replace the pic variable in our initial function declaration.

// function to turn on sales comparison charts
function salesOn(salesPic1, salesPic2) {
   if (document.images) {
      document.images[pic].src=eval(pic + ".src");
      . . .
   }
}

Next, we need to modify the line of code that will change out the image that will show up on the left-hand side. Now, because we are always going to be changing the same image on the left-hand side, we can specify exactly which image we want changed instead of using a variable as we did for the navigation images. So, where we had specified

document.image[pic].src

in the line that changes the navigation image, we will specify the image called salesLeft in our new line of code.

document.images['salesLeft'].src

On the right-hand side of the assignment operator, however, the image we want to show up will depend on which set of years the user has rolled over. We will use the salesPic1 variable that is being passed into the function from the event handler to specify which year IMAGE object we want to use as the source for the image.

=eval(salesPic1 + ".src");

Let's see what our modified line of code looks like in the script.

// function to turn on sales comparison charts
function salesOn(salesPic1, salesPic2) {
   if (document.images) {

   document.images['salesLeft'].src=eval(salesPic1 + ".src");
      . . .
   }
}

This newly modified line will take care of turning on the proper year graphic for the left-hand side; now we need to add another line that will do the same for the right-hand side.

// function to turn on sales comparison charts
function salesOn(salesPic1, salesPic2) {
   if (document.images) {

   document.images['salesLeft'].src=eval(salesPic1 + ".src");
   document.images['salesRight'].src=eval(salesPic2 + ".src");
   }
}

This line is pretty much identical to the first line, except that we are specifying the salesRight image to change and for the script to use the year held in salesPic2 as the new IMAGE object. That will do it for the On function. Let's move on to the Off function for the last step in our script functions. Here is the current Off function.

// function to turn off sales comparison charts
function salesOff(pic) {
   if(document.images) {
     document.images[pic].src= eval(pic + "Off.src");
  }
}

Now let's add the two lines of code that will turn the chart graphics back to their default states once the user has rolled off the set of years.

function salesOff(pic) {
   if(document.images) {
    document.images['salesLeft].src=
"images/sales_comp_left_default.gif";
    document.images['salesRight'].src=
"images/sales_comp_right_default.gif";
  }
}

As in our On function, on the left-hand side of the assignment operator we are explicitly telling the JavaScript engine which images we want to change. On the right-hand side, though, we are doing something new: In the past we have always specified for the engine to look in the source property of another image object for the IMAGE we want to replace. However, because no matter which set of years the user has rolled over, we want to replace it with the original default images, when the user rolls off, we can explicitly tell the JavaScript engine the path to those images, which is what we have done above.

Well, that's it for the changes to the functions; we now simply have to add the event handlers to the right links and we'll be done.

Creating and Inserting the Event Handlers

We will not be swapping out an image that the user has rolled over, as we did in the previous project. Instead, we will swap out two other images when the user has rolled over a text link, so we will place the event handlers inside <a href> tags that are around the text instead of around an image. The event handlers don't really care what is used as the rollover focus, so we can put them in most any object on a page. In this case we're using the text links of the years that the sales charts compare.

<a href=" " class="blueLink">2000 - 2001</a><br>
<br>
<a href=" " class="blueLink">1999 - 2000</a><br>
<br>
<a href=" " class="blueLink">1998 - 1999</a>

Before we insert the handlers, we first need to add the name attribute to the left- and right-hand graphics that we are specifying in our functions.

   <td valign="top" align="left">
     <br><br><img src="images/sales_comp_left_default.gif" alt=""
width="162"
height="87" border="0" name="salesLeft"></td>

   <td valign="top" align="center">
     <font class="blkBldText">Year to Year Sales
Comparrison</font><br>
     <br>
     <a href=" " class="blueLink">2000 - 2001</a><br>
     <br>
     <a href=" " class="blueLink">1999 - 2000</a><br>
     <br>
     <a href=" " class="blueLink">1998 - 1999</a></td>
   <td valign="top" align="left">
     <br><br><img src="images/sales_comp_right_default.gif"
       alt="" width="162" height="87" 
       border="0" name="salesRight></td>

With that done, we can move on to inserting the handlers. The event handlers are going to be very similar to the handlers that we used in our navigation rollovers; there will be both an onMouseOver and onMouseOut. The difference is that we will be calling our new sales functions instead of the rollover functions. We will also not worry about changing the text that shows up in the status bar of the browser. Let's look at link for the years 2000–2001 with the new handlers inserted.

<a href=" " class="blueLink" onMouseOver="salesOn('sales2000',
'sales2001'); return true;" onMouseOut="salesOff(); return true;">2000
- 2001
</a>

In the onMouseOver handler, we are calling the salesOn() function and passing it the two years that we want to compare, first the year we want to show up on the left-hand side, then the year that shows up on the right-hand side. To pass multiple values into a function, you simply need to separate them with a comma. In the onMouseOut handler, we are calling the salesOff() function without passing any values into it. This is because we already know which images we need to change and what we need to change them back to. Let's add the handlers to the two other text links on the page.

<a href=" " class="blueLink" onMouseOver="salesOn('sales2000',
'sales2001'); return true;" onMouseOut="salesOff(); return true;">2000
- 2001
</a><br>
<br>
<a href=" " class="blueLink" onMouseOver="salesOn('sales1999',
'sales2000'); return true;" onMouseOut="salesOff(); return true;">1999
- 2000
</a><br>
<br>
<a href=" " class="blueLink" onMouseOver="salesOn('sales1998',
'sales1999'); return true;" onMouseOut="salesOff(); return true;">1998
- 1999
</a>

We now have handlers inserted for the other two sets of years that we want to compare, which wraps it up for this project. The public relations department will be thrilled with the results and no doubt will soon be looking for other ways we can enhance the annual report. Before they find anything else for us to do, let's go back over how we completed this script.

Reviewing the Script

While some of the functionality for our script was repurposed from our existing rollovers on the homepage, we made some changes and added some new functionality to our rollovers, which deserve to be gone over again. Let's review exactly what we did for this project.

First, we worked with the designer to come up with a new layout for the section and recoded the HTML to match the new layout.

<tr>

   <td valign="top" align="left">
     <br><br><img src="images/sales_comp_left_default.gif"
       alt=""td>

   <td valign="top" align="center">
     <font class="blkBldText">Year to Year Sales
        Comparison</font><br>
     <br>
     <a href=" " class="blueLink">2000 - 2001</a><br>
     <br>
     <a href=" " class="blueLink">1999 - 2000</a><br>
     <br>
     <a href=" " class="blueLink">1998 - 1999</a></td>
   <td valign="top" align="left">
     <br><br><img src="images/sales_comp_right_default.gif"
        alt="" width="162" height="87" border="0"></td>
</tr>

After redoing the HTML, we needed to create four new IMAGE objects to hold the years' sales chart graphics.

<script Language="JavaScript1.2">
<!-- Code after this will be ignored by older browsers

// Creating Image Objects for Rollovers
if (document.images) {
sales2001=new Image(162, 87);
sales2001.src="images/sales_2001.gif";

sales2000=new Image(162, 87);
sales2000.src="images/sales_2000.gif";

sales1999=new Image(162, 87);
sales1999.src="images/sales_1999.gif";

sales1998=new Image(162, 87);
sales1998.src="images/sales_1998.gif";
}

Here are the steps we took in creating the IMAGE objects:

  1. We added a new image for each of the years that we needed a sales chart graphic.

  2. We modified the functions that power the script.

// function to turn on rolled over graphic
function salesOn(salesPic1, salesPic2) {
   if (document.images) {
   document.images['salesLeft'].src=eval(salesPic1 + ".src");

   document.images['salesRight'].src=eval(salesPic2 + ".src");

   }
}

// function to turn off rolled over graphic
function salesOff() {
   if(document.images) {
     document.images['salesLeft'].src=
"images/sales_comp_left_default.gif";
     document.images['salesRight'].src=
"images/sales_comp_right_default.gif";
  }
}
// End cloaking from non JavaScript browsers -->
</script>

We had to do several things to get our functions to where they needed to be for this project:

  1. We copied our On and Off functions from our navigation rollovers and renamed them salesOn and salesOff.

  2. We modified the function to accept two values instead of one to be passed into the function held in the variables salesPic1 and salesPic2.

  3. We modified the statements within our salesOn function. In the first line, we changed the code to specify salesLeft as the image we would be swapping out and for it to use the IMAGE object specified in the salesPic1 variable. We then copied that line of code and changed it to change the salesRight image and use the value in the variable salesPic2 for the new IMAGE object.

  4. We modified the salesOff function. First, we removed the pic variable from the function declaration, as we will not need to pass in any values for this function to work. Next, we modified the first line of code to specify the salesLeft as the image we would be swapping out, and for it to return to the image sales_comp_left_default.gif when the user triggered this function. We then copied that line of code and changed it to change the salesRight image and for it to return to the image sales_comp_right_default.gif again when the user triggered this function.

Finally, we inserted our event handlers into the HTML.

<td valign="top" align="left">
   <br><br>
   <img src="images/sales_comp_left_default.gif" 
      alt="" width="162"
       height="87" border="0" 
       name="salesLeft"></td>

<td valign="top" align="center">
   <font class="blkBldText">Year to Year Sales
       Comparison</font><br>
   <br>
   <a href=" " class="blueLink" onMouseOver="salesOn('sales2000',
'sales2001'); return true;" onMouseOut="salesOff(); return true;">2000
- 2001
</a><br>
   <br>
   <a href=" " class="blueLink" onMouseOver="salesOn('sales1999',
'sales2000'); return true;" onMouseOut="salesOff(); return true;">1999
- 2000
</a><br>
   <br>
   <a href=" " class="blueLink" onMouseOver="salesOn('sales1998',
'sales1999'); return true;" onMouseOut="salesOff(); return true;">1998
- 1999
</a></td>

<td valign="top" align="left">
   <br><br>
   <img src="images/sales_comp_right_default.gif" 
       alt="" name="salesRight" width="162" 
       height="87" border="0"></td>
  1. We added the name attributes salesLeft and salesRight to the left- and right-hand graphics, respectively.

  2. We added the onMouseOver and onMouseOut event handlers to each of the three text links. In the onMouseOver handler, we inserted a call to the salesOn() function and passed it the two years of sales charts that we wanted to compare. In the onMouseOut handler, we inserted a call to the salesOff() function and passed in no values, as none are needed to return the graphics to their default state.

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

  • Repurposing existing script elements for use with new scripts.

  • Passing multiple values into a function.

  • Explicitly specifying the name of the image we wish to change.

  • Explicitly specifying the location of the image we want to use as the source for an image.

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