How to Create Rollovers with JavaScript

excerpted from JavaScript for the World Wide Web: Visual QuickStart Guide, 3rd Edition, by Tom Negrino and Dori Smith

To create a better rollover:
  1. if (document.images) {
        arrowRed = new Image
        arrowBlue = new Image
     
        arrowRed.src =
        -> "images/redArrow.gif"
        arrowBlue.src =
        -> "images/blueArrow.gif"
    }

    This code checks to see if the browser understands image objects (see "A slick way to deal with the browser version problem," next page). If the browser does, the code assigns arrowRed and arrowBlue to two separate image objects. Then, using the .src property, it fills the two objects with the GIFs of the red and blue arrows.

  2. else {
        arrowRed = " "
        arrowBlue = " "
        document.arrow = " "
    }

    This is the code that tells old browsers (ones that failed the test in step 1) what to do. In order to keep from getting error messages in old browsers, we have to create some dummy variables--that is, variables that won't do anything but be created and set to empty. Think of them as placeholders. Create two variables named arrowRed and arrowBlue, and set them to empty. Then create and set document.arrow to empty, too.

  3. <A HREF="next.html" onMouseover=
    -> "document.arrow.src=arrowRed.src"
    -> onMouseout="document.arrow.src=
    -> arrowBlue.src">

    The rest of the rollover gets handled in the link tag. When the user puts the mouse over the blue arrow graphic (onMouseover), the script swaps the blue arrow for the graphic with the red arrow (document.arrow.src=arrowRed.src). When the mouse cursor leaves the area of the graphic, the script reverts the graphic back to the blue arrow.

    red checkTips
    • When you prepare your graphics for rollovers, make sure that none of your GIF images are transparent. Transparent images will show the image they are replacing underneath.

    • Both the original and the replacement images need to have identical dimensions. Otherwise, the browser will resize the images for you, and you probably won't like the distorted result.