• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Chapter 3. Fun with Images > Creating More Effective Rollovers

Creating More Effective Rollovers

To make the illusion of animation work, you need to make sure that the replacement image appears immediately, with no delay while it is fetched from the server. To do that, you use JavaScript to preload all the images into the browser's cache (so that they are already on the user's hard disk when they are needed) and place the images into variables used by your script. Then when the user moves the mouse over an image, the script swaps out one variable containing an image for a second variable containing the replacement image. Script 3.2 shows how it is done. The visible result is the same as in Figures 3.1 and 3.2, but the apparent animation is smoother.

To create a better rollover:

								if (document.images) {
								arrowRed = new Image
								arrowBlue = new Image
								arrowRed.src =
								arrowBlue.src =

This code checks to see if the browser understands image objects (see sidebar). If the browser does, the code creates arrowRed and arrowBlue, two separate image objects. Then, using the .src property, it fills the src properties of the two objects with the GIFs of the red and blue arrows.

								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 an empty string. 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.

<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 anchor 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.



Not a subscriber?

Start A Free Trial

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint