Create a Rollover Class with JavaScript

By: , On Saturday, December 6th, 2008

Here is a simple and very effective way to create rollovers using a images class and id attributes, a naming convention, and the following javascript.

The first thing you will need are the images for your rollovers up,over and down states.

The second thing you’ll need to do is name the images with the same base name and a different substring for each state. Example: myImage_up.jpg, myImage_over.jpg, myImage_down.jpg.

Next in the image element of your html file you will need to add a class which tells the script that this image is a rollover, you will also need to use the images base name as the id.


Lastly add the following script to your document:

window.onload = rolloverInit;
document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) retnode.push(elem[i]);
}
return retnode;
};
function rolloverInit(){
var rollOvers = document.getElementsByClassName("rollover");
for(var i=0; i<rollOvers.length; i++){
setupRollover(rollOvers[i]);
}
}
function setupRollover(thisImage){
//UP
thisImage.outImage = new Image();
thisImage.outImage.src = thisImage.id+"_up.jpg";
thisImage.onerror = thisImage;
thisImage.onmouseout = rollOut;
//OVER
thisImage.clickImage = new Image();
thisImage.clickImage.src = thisImage.id + "_down.jpg";
thisImage.onerror = rollOut;
thisImage.onmousedown = rollClick;
//DOWN
thisImage.overImage = new Image();
thisImage.overImage.src = thisImage.id+"_over.jpg";
thisImage.onerror = rollOut;
thisImage.onmouseover = rollOver;
thisImage.onmouseup = rollOver;
}
function rollOver() {
this.src = this.overImage.src;
}
function rollOut() {
this.src = this.outImage.src;
}
function rollClick() {
this.src = this.clickImage.src;
}

Click the following link to see it in action:
Example

Get the source files by clicking the link below:
Download

Note: Your naming convention you use for your files must match that used in the script, if your images are in a subdirectory you must add the directory name to the source string in the script, example: thisImage.id+”_over.jpg” becomes “images/”+thisImage.id+”_over.jpg”.

One Response to “Create a Rollover Class with JavaScript”

  1. Mike Thornley Says:

    I liked this post, Dell and found it very useful. Thanks. =D>
    .-= Mike Thornley´s last blog ..Developers & Designers in Manchester…. =-.

Loading Facebook Comments ...

© Wardell Design 2019
Entries (RSS) and Comments (RSS).