<<< Home << Web < Rollovers Top Bottom < Prev Next >

JavaScript Rollovers

A Complete Example

This page shows a complete example of all of the JavaScript and HTML code needed to do a rollover. The following pages explain all of this code.

There are lots of different ways to do rollovers. The method I've used here works with Netscape 3+, Internet Explorer 4+ and Opera. Since it uses the name attribute of the <img> tag, you'll have to specify the HTML 4.01 DTD in order to validate cleanly (HTML 4.0 did not include the name attribute). Since the id attribute will eventually replace the name attribute, you should include both id and name in your <img> tags even though name is the only one that is needed in all browsers that currently support image rollovers.

Skin #4

There are two parts to the rollover code. The first part is JavaScript code that resides in the <head> section of the document:

<script language="javascript" type="text/javascript"> <!--

//====================================================
// preloadImg() - Preloads an image
//
// Argument: String containing URL of image to preload
// Returns:  Image object created for the image
// Author:   Larry Coats
//====================================================
function preloadImg (zsUrl)
{
  // Prevent alerts in IE 3 and Netscape 2
  if (!document.images) return null;

  // Create an image object and preload the image
  var xo = new Image();   // Create the image object
  xo.src = zsUrl;         // Set URL - Preloads
  return xo;              // Return the image object
}

//====================================================
// swapImg() - Swaps an image
// Arguments:
//   A string containing the name in the <img> tag
//   A string containing the name of the preloaded
//     image object of the image to swap in
// Author:   Larry Coats
//====================================================
function swapImg (zsImg, zsPre)
{
  if (document.images) {
    var xS = "document." + zsImg + ".src = " + zsPre + ".src";
    eval (xS);
  }
}

//====================================================
// Preload the images
//====================================================
var gmSkin04  = preloadImg ("images/skin04.jpg");
var gmSkin04n = preloadImg ("images/skin04n.jpg");

//--> </script>

The second part of the rollover code is the image definition in the HTML code:

<a href="#" onclick="return false;"
   onmouseover="swapImg ('im1', 'gmSkin04n');"
   onmouseout="swapImg ('im1', 'gmSkin04');">
  <img src="images/skin04.jpg" width="185" height="185"
     border="0" id="im1" name="im1" alt="Skin #4"></a>

<<< Home << Web < Rollovers Top Bottom < Prev Next >