JavaScript Rollovers: Creating an Image Object - Doc JavaScript | WebReference

JavaScript Rollovers: Creating an Image Object - Doc JavaScript

Creating an Image Object

Creating an Image object is as simple as creating any other object in JavaScript:

var variableName = new Image();

The following statement preloads the desired image:

variableName.src = "imageURL.gif";

Notice the use of the src property in the preceding statement. It enables you to associate an actual image with an instance of the Image object.

A JavaScript rollover requires at least two images. For example, take a look at the following images:

<IMG SRC="advann.gif" HEIGHT="24" WIDTH="120" NAME="advan">

<IMG SRC="advana.gif" HEIGHT="24" WIDTH="120" NAME="advan">

Note that the active and inactive images in a rollover must both be the same size. Otherwise, the active image is automatically adjusted to the size of the inactive image.

The following script shows how to combine these two images into an appealing JavaScript rollover:

if (document.images) {
  var advanoff = new Image(); // for the inactive image
  advanoff.src = "advann.gif";
  var advanon = new Image(); // for the active image
  advanon.src = "advana.gif";
function act() {
  if (document.images)
    document.images.advan.src = advanon.src;
function inact() {
  if (document.images)
    document.images.advan.src = advanoff.src;

The corresponding HTML code for this rollover is:

<A HREF="advantages.html"
   onMouseOver="act()" onMouseOut="inact()">
<IMG SRC="advann.gif" HEIGHT="24" WIDTH="120" 
    NAME="advan" BORDER="0" ALT="Netscent Advantages"></A>

Here's the result:

Netscent Advantages

Try placing the mouse over the image. If you click it, this page will reload, because the URLs in our example aren't real.

Created: August 21, 1997
Revised: March 30, 1998