Tuesday, May 27, 2008

Rollovers / Image Swap


Description

We have all dealt with clunky Javascript functions to achieve image rollover effects (image swapping) with the use of mouseover and mouseout event handling. The purpose of this article will be to demonstrate how to do these rollovers, but in a simpler way.

Basically, the code is going to sweep through the page and determine if an image is swappable. An image is determined to be swappable by using a custom attribute "swap=true".

<img src="../logo.gif" alt="logo" swap="true" />

The image "logo.gif" will now be swapped with the image "logo_ro.gif" during a mouse rollover event. Note: you must give your rollover image the same name as the original image and append "_ro" to it. You can change "_ro" to another string constant within the code if you prefer.

/**
* @projectDescription Image Swap Module
*
* @author Ryan Estes http://www.codeapedia.com
* @version 0.1
*/

var _NAMING_CONVENTION_IMAGE_SWAP = "_ro";
var image_module =
{
run : function() {
var obj = null;
var arr = document.getElementsByTagName("img");
for(var i = 0; i < arr.length; i++)
{
obj = arr[i];
if(image_module.__isSwappable(obj))
{
image_module.__addSwapEvents(obj);
image_module.__preLoad(obj);
}
}
},
__preLoad : function(img) {
var ext = image_module.__getExtension(img);
var objImage = document.createElement("img");
objImage.src = img.src.replace(
ext,
_NAMING_CONVENTION_IMAGE_SWAP + ext);
},
__getExtension : function(img) {
var i = img.src.lastIndexOf(".");
return ext = img.src.substring(i,img.src.length);
},
__isSwappable : function(img) {
return img.getAttribute("swap") == "true";
},
__addSwapEvents : function(img) {
img.onmouseover = function() {
var ext = image_module.__getExtension(img);
this.src = this.src.replace(
ext,
_NAMING_CONVENTION_IMAGE_SWAP + ext);
}
img.onmouseout = function() {
this.src = this.src.replace(
_NAMING_CONVENTION_IMAGE_SWAP,
'');
}
}
};

image_module.run();

There you have it! Stash this code into an external javascript file called codeapedia.image_module.js and import it at the bottom of your page.

1 comments:

Anonymous said...

Very nice!

 

blogger templates | Make Money Online