Joe Maller:JavaScript: Basic JavaScript Rollovers

A simple JavaScript tutorial showing how to replace an image when the cursor rolls over it.

When I first wrote this page Netscape had 85% of the browser market and rollovers were only seen on "multimedia" CD-ROMs. Times have changed. Now rollovers are everywhere and Netscape is 85% dead.

I saw my first rollover on one of Netscape's 3.0 Preview pages, and I immediately wanted to know how make one. With the example page's source code, Netscape's developer pages and a few wonderful web tutorials, I managed to figure it out for myself. This page is my way of thanking all those who helped me learn.

Five years later, this is still the most visited page on my site.
(please feel free to check out the rest of the site)

This is the third major revision of the page. Everything still works, so there wasn't much to change, I revised it a little, corrected a typo that no one ever commented on*. The original page is still here.

Starting the Script

JavaScripts can be placed anywhere in an HTML document, but it's become customary to place them inside the <HEAD> section, just after the document's <TITLE> tagset.

The beginning of a simple HTML page with space for a JavaScript looks like this:

<HTML>
<HEAD>
<TITLE>
  Basic JavaScript Rollovers by Joe Maller
</TITLE> 
<SCRIPT LANGUAGE="JavaScript">
  <!-- Hide from old browsers  
(JavaScript will go here)
  // Stop hiding from old browsers -->
</SCRIPT> 
</HEAD>

The <SCRIPT LANGUAGE="JavaScript"></SCRIPT> tagset separate the script from the rest of the document. It's also a good idea to enclose the entire content of the script tagset in an HTML comment. This will exempt the script code from accidentally displaying on older browsers.

Comments are ignored information. They usually serve as author's notes about how the code works. HTML's syntax for comments is <!-- words -->. Everything between the start and end hyphen-arrows is ignored by the browser.

In JavaScript, two slashes // indicate that all text that follows on the same line is ignored. Comments can say anything, I occasionally replace the "hide/stop hiding..." text with something more interesting.

Declaring Images in the Script

The first step in creating a rollover is to tell JavaScript about the images the rollover will use. This will cause JavaScript to load the images into memory before they are visible. Once the images are cached, the image swaps can happen instantaneously.

It is possible to have a rollover without declaring and preloading the images, but before the images changes the browser must first open a new connection and load the second image. This takes long enough, even on fast connections, to make the rollover less effective.

To preload the images, each is declared in two lines of an array. Arrays are like mini files, storing several pieces of information all in one place. Our array, named Rollimage, will store the image locations (sources) and sizes:

Rollimage = new Array()
   
Rollimage[0] = new Image(100,150) 
Rollimage[0].src = "your_image.gif" 

Rollimage[1] = new Image(100,150)
Rollimage[1].src = "your_other_image.gif"

The first line initializes the array, and following numbered sets of lines are the declaration of each additional image. The first line of each set declares the image's size and the second assigns its address. The numbers inside the parentheses refer to the width and height of the image, in that order. All of my example images are in the same folder as the HTML file so they can be addressed with only their name, a non-local image would have its full URL in the second line.

Early versions of JavaScript were case sensitive. The newest version claims to be partly case sensitive but the boundaries of when it is and isn't are unclear. To be on the safe side, be sure to refer to your variables and arrays with consideration of case. TheDog is different than thedog.

Naming Image Objects

To replace an image JavaScript needs a way to identify which image to replace. Do this by including a name attribute in the <IMG> tag or learning to refer to images in JavaScript's Array syntax:

document.images[2]

The browser counts every image on a page and refers to them numerically starting from the first image. The above refers to the third image tag in the HTML document (count like a computer, zero comes first).

I've found named images easier to keep track of so that's what I use in this example. The following image is named "Rupert":

<IMG NAME="Rupert" SRC="some.gif">

JavaScript can't activate a rollover in an unlinked image tag. Here is the HTML code for the changing image:

<A HREF="link.html"
  onMouseOver="SwapOut()"
  onMouseOut="SwapBack()">
<IMG NAME="Rupert"
  SRC="your_image.gif"
  WIDTH="100"
  HEIGHT="150">
</A>

What's "onMouseOver"?

onMouseOver and onMouseOut are event handlers, they tell JavaScript what to do when an event occurs. The mouse cursor passing over the linked image is defined as an event because of these bits of code. onMouseOver="blorg()" would tell JavaScript to execute the function blorg().

Functions (Almost done!)

Functions are a predefined set of commands that JavaScript only executes when called, they are usually defined in the first <SCRIPT> section of the document. The standard format for defining a function is:
function SwapOut() {
  document.Rupert.src = Rollimage[1].src;
  return true;
} 

That function's name is SwapOut(). The parentheses can be used in more complex scripts to send data that the function will work with. The guts of the function are written between the {} brackets.

SwapOut() tells the Rupert image's src attribute to equal Rollimage[1].src, which is the second image from the array created earlier. In english, it changes the source of the Rupert image. The other function in this document, SwapBack(), is almost the same as SwapOut() except that it switches back to the first image in the array:

function SwapBack(){
  document.Rupert.src = Rollimage[0].src;
  return true;
}

Putting It All Together

That's basically it. Following is the complete code for a simple document with one rollover image. Try it out.

<HTML>
<HEAD>
<TITLE>
  Basic JavaScript Rollover by Joe Maller
</TITLE>
<SCRIPT LANGUAGE="JavaScript">
  <!-- hide from non JavaScript Browsers

  Rollimage = new Array()

  Rollimage[0]= new Image(121,153)
  Rollimage[0].src = "joe_open.jpg"

  Rollimage[1] = new Image(121,153)
  Rollimage[1].src = "joe_blink.jpg"

  function SwapOut(){
    document.Rupert.src = Rollimage[1].src;
    return true;
  }

  function SwapBack(){
    document.Rupert.src = Rollimage[0].src; 
    return true;
  }

// - stop hiding          --> 
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<P align="center"> 
<A HREF="http://www.joemaller.com/"
  onmouseover="SwapOut()"
  onmouseout="SwapBack()">
<IMG SRC="joe_open.jpg"
  NAME="Rupert" 
  WIDTH=121
  HEIGHT=153
  BORDER=0>
</A> 
</P>
<P align="center"> 
  If you use this, please give me credit.
</P>
</BODY> 
</HTML> 

You can also copy that source code here:

Notes and Frequently Asked Questions

  • Quotation marks
    Misplaced quote marks cause unbelievable problems. Make sure thatsingle and double quote marks are properly nested and closed. The same goes for Parentheses and Curly Braces.

  • Naming
    When changing names of objects, be sure to change every instance of that name everywhere in script and each named object on the page. No two objects should have the same name.

  • LOWSRC
    If you use a Low Source in your image tags, you might experience unwanted reloads of the LOWSRC image before every swap.

  • Image Size - The size of the image is set by the image you will be replacing. Replacement images will be stretched to fit. Setting the image size in the array seems to be optional, images will stretch to fit the size specified in the <IMG> tag. If the images are different sizes and the <IMG> tag does not specify height and width, the rollover will act unpredictably, possibly using the images at their natural size.

  • Multiple Image Rollovers
    While you can duplicate this script with different names, a more efficient solution is on my multiple image rollover page.

Other Stuff

Thanks to Lynda Weinman for including my original rollover page in her book <designing web graphics.2> (the yellow one). While this page no longer appears in the revised book, I appreciate the inclusion and am thankful for all her support over the years.

Thanks also to all the poeple who have written about this page. It's been great to hear from you and to see all the site using this code.

* The original page included a typo that even made it past the editors of Lynda's book, I didn't actually notice it until I saw it in print. The first comment to hide the script read:

 <!-- hide from none JavaScript Browsers

The "none" thing was a mistake, usually I try to be better with language than that. I meant to say "non-JavaScript". I can't believe how much of your time and mine I just wasted by telling that story.

Conclusions

If you use this script, please include a link to my site so other people can share this information too.

I'm working on a page that will link to all the sites using my code, send me a note so I can include yours too. The more pages we link, the more people will see them.

Joe Maller

 
page last modified: October 23, 2017
Copyright © 1996-2003 Joe Maller