Home > Articles > Web Development > Ajax and JavaScript

Advanced Javascript Mouseovers

Go beyond the basic JavaScript mouseover and learn how to add preloaded images with submenus and stylesheets. Explore some sample code and the meaning behind it with an in-depth example.
This chapter is from the book

How Rollovers Work

To understand how rollovers actually work, we have to understand how JavaScript sees the world. When a Web page is loaded into a browser, the browser does more than just format and present the HTML for the user to look at. Behind the scenes, the browser also has a JavaScript engine that examines the page as it is being loaded and organizes the page into a formal structure that it can understand. For example, when the JavaScript engine sees the <body> tag, it creates an object called "document" and places all the parts of that page into the document object.

JavaScript follows certain rules when dissecting and organizing a Web page. For example, all of the images on the page, whether they're massive things or tiny, single-pixel gifs, are placed into an array called "images." This images array lives inside the document object. For example, if you wanted JavaScript to look at the first image in your Web page, the code would look like this:

document.images[0]

Remember, arrays start counting at zero, not one.

Using the images array like this when you're creating rollovers is such a bad idea that we're not even going to look at it in an example. We'll look at a few better ways, then come back and see why using image array numbers isn't recommended.

So how else can you point to a certain image using JavaScript? You can give the image a name, then use that name in JavaScript. Let's say we're building a navigation bar with rollovers, and one of the items is "news." Here's what the HTML could look like:

<img name="news" src="images/nav_news_off.gif">

Notice we gave the image the unimaginative but predictable name of "news." So how would you point to this image using JavaScript? There are actually two ways:

document.images['news']

and

document.images.news

These both work fine. In our examples, we'll be using the latter form because it's easier to read.

Replacing Images

So we know how to point to an image, but how do we replace it? Simple: We use the src property of images as follows:

document.images.news.src

You can now assign this src property to any URL that points at an image as in the following:

document.images.news.src = "images/news_on.gif"

or

document.images['news'].src =
  "http://images.shelleybiotech.com/home/news.gif"

These statements load the new image into the old image's place. It's not a complete replacement, though—the new image is loaded into the old image's dimensions. Let's say you have an image that's 100 pixels wide and 200 pixels high. Using the src property, you replace that old image with a new one that's also 100 pixels wide, but it's taller: It's 300 pixels high. That new image will appear in the old image's place, but it will be squashed down to 200 pixels in height. Thus, you have to make sure that when you're replacing one image with another, they are exactly the same size.

Shelley Biotech

Let's start coding. We'll be building the home page for a fictional company called Shelley Biotechnologies. The home page looks like Figure 1–1.

Figure 1-1Figure 1–1 Shelley Biotech home page

It's pretty simple. What do our rollovers look like? If the user rolls over "Products," it should look like Figure 1–2.

Figure 1-2Figure 1–2 Rollover example

Before we jump into rollovers, let's build the basic page, which is just comprised of a bunch of images. These images are in Figure 1–3.

Figure 1-3Figure 1–3 The nonrollover images

You can download all the images and code for this chapter (and all the other chapters) at http://www.wire-man.com/advjs. I recommend it—you'll learn much better when you do the code yourself. The code for the home page (again, without any rollovers yet) is in Example 1–1.

Example 1–1 The Shelley home page, sans rollovers

<html>
<head>
<title>Shelley Biotech</title>
<style type="text/css">
    #header { position: absolute; left: 30; top: 30;}
    #tag   { position: absolute; left: 250; top: 77;}
    #gal   { position: absolute; left: 514; top: 69;}
    #nav   { position: absolute; left: 0; top: 114;}
    #feature { position: absolute; left: 10; top: 220;}
    #copyright { position: absolute; left: 350; top: 490;}
</style>
</head>

<body bgcolor="#FFFFFF" topmargin="0" leftmargin="0">

<div id="header">
    <img src="images/shelley_biotech.gif">
</div>

<div id="tag">
    <img src="images/tag_line.gif">
</div>

<div id="gal">
    <img src="images/freaky_gal.jpg">
</div>

<div id="nav">
<table border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td><img src="images/nav_start.gif"></td>
      <td>
        <a href="news/">
        <img name="news" src="images/nav_news_off.gif"
        border="0"></a></td>
      <td>
        <a href="products/">
        <img name="products" src="images/nav_products_off.gif"
        border="0"></a></td>
      <td>
        <a href="research/">
        <img name="research" src="images/nav_research_off.gif"
        border="0"></a></td>
      <td>
        <a href="store/">
        <img name="store" src="images/nav_store_off.gif"
        border="0"></a></td>
      <td>
        <a href="about/">
        <img name="about" src="images/nav_about_off.gif"
        border="0"></a></td>
    </tr>
</table>
</div>

<div id="feature">
    <img src="images/features.jpg">
</div>

<div id="copyright">
    <img src="images/copyright.gif">
</div>

</body>
</html>

How the Code Works

The only real key to understanding this code is to realize that CSS (or just "stylesheets") are being used to place the images. If stylesheets are new to you, refer to the side note for a quick tutorial.

Cascading Style Sheets

Cascading Style Sheets (CSS) allow you to define chunks of content, or layers, in your HTML page. This happens in two steps. The first step is to define the layer, where you describe its name, where it lives on the Web page, and maybe some other attributes. This is done in the header. In Example 1–1, it occurred here:

<style type="text/css">
    	#header { position: absolute; left: 30; top: 30;}

</style>

We defined a layer called "header" and said it must be at 30 pixels from the left of the browser window and 30 pixels from the top of the browser window.

This is only the first step. Now that we've defined the layer, we have to create the content that actually lives in the layer. This happens in the body of the Web page.

<div id="header">
    <img src="images/shelley_biotech.gif">
</div>

You define a layer by wrapping some HTML with a <div> tag, and giving that <div> tag an "id" matching the name of the layer defined above. In this case, the shelley_biotech.gif image then appears at 30 pixels over and 30 pixels down.

There's a lot more to stylesheets. If you're really interested, by all means check out Essential CSS & DHTML for Web Professionals (by me).

The whole series of navigation images lives in a table. I included an anchor tag, but it obviously doesn't do very much. It's just a placeholder, and we'll be adding to it soon.

Also notice that all of the images in the navigation were given names:

<img name="news" src="images/nav_news_off.gif">
<img name="products" src="images/nav_products_off.gif">
<img name="research" src="images/nav_research_off.gif">
<img name="store" src="images/nav_store_off.gif">
<img name="about" src="images/nav_about_off.gif">

I've taken out the border attribute here so they're easier to read.

Before we get much further, you should see the actual rollover images themselves. Here they are, in Figure 1–4.

Figure 1-4Figure 1–4 Rollover images

As the code exists right now, these names don't do anything. They just sit there, waiting to be invoked. Let's start with some JavaScript to do that.

Rollover Function

We'll create a single function that handles the rollover and another function to handle the rollout. Let's start with the rollover in Example 1–2.

Example 1–2 The rollover function

function rollOver (imgName)
{
    eval("document.images." + imgName + ".src =
    'images/nav_" + imgName + "_on.gif'")
}

How the Code Works

This may look a little confusing at first, especially if you aren't familiar with the eval() method. Let's step back and look at this method's goal. We want to send it the name of the navigation item that was just rolled over, because it will then swap out the old image for the new one. That is, if the user rolls over the Research image, we want to execute this JavaScript:

document.images.research.src =
    'images/nav_research_on.gif'

Since we want the name of the image to allow different values, this line of code has to be able to change:

document.images.NameOfImage.src =
    'images/nav_NameOfImage_on.gif'

In other words, we want to dynamically create JavaScript code. The eval() method handles this nicely for us. Eval() works by taking whatever string is inside its parentheses and executing that string as if it were a line of JavaScript code. In this case, if "research" was passed to the function, this is what eval() would see this string:

"document.images.research.src =
    'images/nav_research_on.gif'"

Eval() would proceed to execute this code as if it weren't a string, and thus the image nav_research_on.gif replaces nav_research_off.gif.

Great. Now the image is present and the function is in place. All we need to do right now is to call that function at the appropriate time. Example 1–3 shows the HTML that will do that:

Example 1–3 Calling the function

<a href="research/" onMouseOver="javascript:rollOver('research')">
<img name="research" src="images/nav_research_off.gif"
border="0"></a>

How the Code Works

The code that fires off our rollover function is the onMouseOver bit. Whenever the user's mouse rolls over the image, the JavaScript in the attribute is executed. In this case, the function called rollOver is activated, and the value "research" is sent to that function. Notice that onMouseOver occurs in the anchor tag, not in the image tag. If you haven't done mouseovers before, this can seem a little counterintuitive.

Go ahead and try this code. When you roll over the research image, it should be replaced with the blue-green image. Now roll out. Nothing happens. The research image stays turned on no matter what you do. Clearly, we need a way to set the image back to its original state when the user moves the mouse away from the image. The code to do this is almost exactly like the rollover code:

function rollOut (imgName)
{
    eval("document.images." + imgName + ".src =
     'images/nav_" + imgName + "_off.gif'")
}

This function is an almost exact copy of the rollOver function we saw earlier. The only thing different about this code is that instead of using _on in the image name, we're using _off. That's it.

But since this is an Advanced JavaScript book, let's alter this a bit. You could easily use the code below instead:

function rollOut (imgName)
{
    document.images[imgName].src =
      eval("'images/nav_" + imgName + "_off.gif'")
}

This isn't wildly different—just a small tweak that more obviously treats images as an array, and now only the right side of the statement needs an eval() method. It makes no difference to the user which code is used—the rollover works either way. Choose whichever method you prefer.

This is the only JavaScript we need. The only step that's left is to call these functions from each of the navigation images, as in Example 1–4.

Example 1–4 Calling rollover functions from all navigation images

<td>
<a href="news/"
    onMouseOver="javascript:rollOver('news')"
    onMouseOut="javascript:rollOut('news')">
<img name="news" src="images/nav_news_off.gif"
    border="0"></a></td>
<td>
<a href="products/"
    onMouseOver="javascript:rollOver('products')"
    onMouseOut="javascript:rollOut('products')">
<img name="products"
    src="images/nav_products_off.gif"
    border="0"></a></td>
<td>
<a href="research/"
    onMouseOver="javascript:rollOver('research')"
    onMouseOut="javascript:rollOut('research')">
<img name="research" src="images/nav_research_off.gif"
    border="0"></a></td>
<td>
<a href="store/"
    onMouseOver="javascript:rollOver('store')"
    onMouseOut="javascript:rollOut('store')">
<img name="store" src="images/nav_store_off.gif"
    border="0"></a></td>
<td>
<a href="about/"
    onMouseOver="javascript:rollOver('about')"
    onMouseOut="javascript:rollOut('about')">
<img name="about" src="images/nav_about_off.gif"
    border="0"></a></td>

That's it! To make your life a little easier, here's Example 1–5, with the whole page in a single listing:

Example 1–5 The whole page

<html>
<head>
<title>Shelley Biotech</title>

<style type="text/css">
#header          { position: absolute; left: 30; top: 30;}
#tag          { position: absolute; left: 250; top: 77;}
#gal          { position: absolute; left: 514; top: 69;}
#nav          { position: absolute; left: 0; top: 114;}
#feature           { position: absolute; left: 10; top: 220;}
#copyright          { position: absolute; left: 350; top: 490;}
</style>

<script language="JavaScript">

function rollOver (imgName)
{
    eval("document.images." + imgName + ".src = 'images/nav_" +
    imgName + "_on.gif'")
}

function rollOut (imgName)
{
    document.images[imgName].src = eval("'images/nav_" +
imgName +
    "_off.gif'")
}

</script>

</head>

<body bgcolor="#FFFFFF" topmargin="0" leftmargin="0">
<div id="header">
<img src="images/shelley_biotech.gif">
</div>

<div id="tag">
<img src="images/tag_line.gif">
</div>

<div id="gal">
<img src="images/freaky_gal.jpg">
</div>

<div id="nav">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td><img src="images/nav_start.gif"></td>
<td>
<a href="news/"
    onMouseOver="javascript:rollOver('news')"
    onMouseOut="javascript:rollOut('news')">
<img name="news" src="images/nav_news_off.gif"
    border="0"></a></td>
<td>
<a href="products/"
    onMouseOver="javascript:rollOver('products')"
    onMouseOut="javascript:rollOut('products')">
<img name="products" src="images/nav_products_off.gif"
    border="0"></a></td>
<td>
<a href="research/"
    onMouseOver="javascript:rollOver('research')"
    onMouseOut="javascript:rollOut('research')">
<img name="research" src="images/nav_research_off.gif"
    border="0"></a></td>
<td>
<a href="store/"
    onMouseOver="javascript:rollOver('store')"
    onMouseOut="javascript:rollOut('store')">
<img name="store" src="images/nav_store_off.gif"
    border="0"></a></td>
<td>
<a href="about/"
    onMouseOver="javascript:rollOver('about')"
    onMouseOut="javascript:rollOut('about')">
<img name="about" src="images/nav_about_off.gif"
    border="0"></a></td>
</tr>
</table>
</div>

<div id="feature">
    <img src="images/features.jpg">
</div>

<div id="copyright">
    <img src="images/copyright.gif">
</div>

</body>
</html>

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