Image

YARS

(yet another rollover script)


My starting this community got my sister asking me to show her a thing or two about Javascript, and I thought I'd show her something simple like image rollovers. Well, as I proceded to show her "better ways" to do things, the script evolved, and what resulted was the most concise, versatile, and easy-to-use image rollover script I've ever seen, if I do say so myself. :)





/* First, (in the document HEAD) I create an array for the images to go in: */



var Images = new Array();       // create the Images array


/* Each element of the "Images" array will be another array itself. Each of these arrays will have two elements: the "on" and "off" states of the rollover. The "newImage" function makes it easy to add new images: */



function newImage(Key, imgOff, imgOn)
// function for adding a new image rollover set to the Images array --
// "Key" should match the NAME of the IMG tag associated with the new rollover.
// "imgOff" should match the SRC of that IMG tag.
// "imgOn" is the URL for the replacement image.
{
    if (document.images)
    {
        Images[Key] = new Array();
        Images[Key][0] = new Image();
        Images[Key][0].src = imgOff;
        Images[Key][1] = new Image();
        Images[Key][1].src = imgOn;
    }
}


/* Then the function that performs the actual rollover switch: */



function swapImage(theTag, OnOff)
// function for swapping a certain image
{
    if (document.images)
    {
        theTag.src = Images[theTag.name][OnOff].src;
    }
}


/* So that's all the stuff that doesn't change. Now to initialize the particular rollovers for your page. Let's say you want three rollovers, for "home", "about", and "thingy": */



newImage("home", "path/to/home-off.jpg", "path/to/home-on.jpg");
newImage("about", "path/to/about-off.jpg", "path/to/about-on.jpg");
newImage("thingy", "path/to/thingy-off.jpg", "path/to/thingy-on.jpg");


And that's all inside a SCRIPT tag in the document HEAD. Then, in the HTML of the BODY, the "home" IMG tag, for example, would look like this:



<IMG
    NAME="home" 
    SRC="path/to/home-off.jpg"
    onMouseOut="swapImage(this, 0);"
    onMouseOver="swapImage(this, 1);"
>


Just change the NAME and the SRC for the other images.



I just thought I'd share this, because personally, I think this is much better than most other rollover scripts I've seen, which involve a lot more tedious editing of code.



One thing I'm not sure of is this putting "onMouseOver" and "onMouseOut" on the IMG tag itself. I've only tested it in Internet Explorer 5 and Mozilla 1.0, and I don't know if it'll work in other/older browsers. If it doesn't, that can be fixed by moving the "onMouseOver" and "onMouseOut" from the "IMG" tag to an enclosing "A" tag, and replacing "this" with "document.home", "document.about", etc.



I'll stick a working demo of it up on my web site as soon as I get a chance.