Better Image Rollovers


© Muhammad Ali Shah
Articles in this Topic    Discussions in this Topic


Skill Level: Intermediate
Skills Required: JavaScript Basics, document Object, Arrays


Abstract: Image rollovers are inevitable if you are serious in web business. There are many creative ways of using the technique, but mostly image rollovers are used to turn a black n' white image into color. This article explains you how you can create better image rollovers by pre-loading images. For basic information on image rolloever, see my other article.


Need for Preloading Images: Let's first discuss what is the difference between a simple image rollover and one with preloaded images. A simple image rollover mechanism loads a page with dark / black n' white images; when the mouse is moved over an image, a colored / light image is shown in its place. Though it works alright on your hard disk; this technique won't work for the web. An image can't be downloaded at once when the mouse moves over an image. Thus, its better to pre-load the images and not to show them. These pre-loaded images are shown only when the mouse moves over the image.


Ground Work: JavaScript is mostly written in the head part of the HTML page, because the head part gets loaded first. Using the same concept, we can pre-load images by creating image object(s) within the head part. A new image object can be created by var x = new image (width, height). This creates an image named x with given width and height. It doesn't contain a picture yet! To load a file into this image, we can write something like x.src = fileName.ext. Of course, the extention should be .gif or .jpg.

Once images have been pre-loaded this way, we can write a function that replaces one image with another. All this is explained with the help of an example below.


Example: This example takes two images of a clock of exactly same width and height. One of them is grayscaled image, named dark.gif and the other one is colored, named light.gif.


Head Part: The head part of this example consists of only one function, showImage. The showImage() function will become more clear when we say the way it's called. The source code in the beginning pre loads the clock images as explained above.

<head>
<title>Image Rollover Example...</title>

<script language="JavaScript"><!--
// pre load images
var clock0, clock1; // to hold light and dark imgs

Book Cover
Colored
     

Go To Page: 1 2


Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo