The code to generate this effect:
// To make sure this script runs AFTER the page finishes downloading,
// we have to add it to the list of "window.onload" events. It is important
// to preserve other functions that might be scheduled to execute "onload",
// so we set the old "window.onload" event to a variable for later use:
window.image_mouseover_effect_oldLoad = window.onload ? window.onload : function(){};
// Now we design our own onload function, which will find all the images
// that have "image_mouseover_effect" in their class (called "className"),
// and then modify each image so it has the mouseover effect:
window.onload = function()
{
// First, store an array of all
elements in the document:
var allImages = document.getElementsByTagName("img");
// Then loop through each
element in that array:
for(var img in allImages)
{
// Each
needs a function for the "onmouseover" (mouse entering) event:
allImages[img].onmouseover = function()
{
// This next part makes the image's "src" (the image's location)
// something like "imageX_over.jpg" (from the original "imageX.jpg"):
this.src = this.src.substring(0,this.src.lastIndexOf(".")) + "_over" + this.src.substring(this.src.lastIndexOf("."), this.src.length);
};
// Like the "onmouseover" event, we need to handle the "onmouseout" (mouse leaving) event:
allImages[img].onmouseout = function()
{
// This next part reverts the image's "src" (the image's location)
// back to something like "imageX.jpg" if it has "_over" in it:
if(this.src.indexOf('_over') > -1)
this.src = this.src.substring(0,this.src.lastIndexOf("_over")) + this.src.substring(this.src.lastIndexOf("_over") + "_over".length, this.src.length);
};
// (this is the end of our
traversal loop)
}
// Lastly, we need to call the "window.onload" function that we replaced,
// so our image rollover script doesn't disable other scripts on the same page:
window.image_mouseover_effect_oldLoad();
// And that's it! Just one last brace bracket to end off our "window.onload" function:
};
And, now the clean (comment-free) version:
window.image_mouseover_effect_oldLoad = window.onload ? window.onload : function(){};
window.onload = function() {
var allImages = document.getElementsByTagName("img");
for(var img in allImages) {
allImages[img].onmouseover = function() {
this.src = this.src.substring(0,this.src.lastIndexOf(".")) + "_over" + this.src.substring(this.src.lastIndexOf("."), this.src.length);
};
allImages[img].onmouseout = function() {
if(this.src.indexOf('_over') > -1)
this.src = this.src.substring(0,this.src.lastIndexOf("_over")) + this.src.substring(this.src.lastIndexOf("_over") + "_over".length, this.src.length);
};
}
window.image_mouseover_effect_oldLoad();
};