Tips
All Tips ]

Replace an image with another when the mouse pointer moves over it

You have probably already seen the dynamic substitution of one image for another when the mouse pointer passes over it. The two images must be loaded when the page itself is loaded, and the pointer over the currently displayed image must also be detected. Then the image swap is carried out with a JavaScript piece of code, which you insert in the appropriate location in your page. Insert the following script between the <HEAD> and </HEAD> tags:

<SCRIPT LANGUAGE="Javascript">
<!-- Swap images
function Permut (flag,img) {
   if (document.images) {
        if (document.images[img].permloaded) {
            if (flag==1) document.images[img].src = document.images[img].perm.src
            else document.images[img].src = document.images[img].perm.oldsrc
        }
   }
}
function preloadPermut (img,adresse) {
   if (document.images) {
        img.onload = null;
        img.perm = new Image ();
        img.perm.oldsrc = img.src;
        img.perm.src = adresse;
        img.permloaded = true;
   }
}
// -->
</SCRIPT>

Then replace the usual IMG tag with the following code to call the images:

<A HREF="index.html" onMouseover="Permut(1,'IMG1');" onMouseout="Permut(0,'IMG1');">
<IMG SRC="Image1" border=0 NAME="IMG1" onLoad="preloadPermut(this,'Image2');" ></A>

where index.html is the document to which the image points to, Image1 is the displayed image when the page is loaded, and Image2 is the image substituted for Image1 when the mouse pointer is passed over it.

Discover all Webmaster tips.