User Tools

Site Tools


notes:javascript:rolloverimages

Rollover Images in JavaScript

/*
  Script: RolloverImages.js
  Date Created: August 24, 2009
 
  Instruction:
  1. Include the RolloverImages.js script in the page header:
     <script type="text/javascript" src="RolloverImages.js"></script>
  2. Call the PreloadRolloverImages() function from the onload event of the Body tag:
     <body onload="PreloadRolloverImages();">  
  3. Add enableRolloverImages, rolloverImageSrcOff, and rolloverImageSrcOn tags to an image you want to rollover:
     <img id="imgRollover" src="ImgOff.jpg" border="0" enableRolloverImages="True" 
          rolloverImageSrcOff="ImgOff.jpg" rolloverImageSrcOn="ImgOn.jpg" />  
  4. Enable or disable the rollover effect by setting the enableRolloverImages attribute to 'true' or 'false'.
*/
 
// A global array to keep the preloaded images. It is not used anywhere.
var preloadedRolloverImages = new Array();
 
function PreloadRolloverImages()
{
    var j=0;
    for(var i=0; i<document.images.length; i++)
    {
        var img = document.images[i];
 
        // Two-step conditional statement is required for Firefox and Chrome.
        if (typeof(img.getAttribute("enableRolloverImages")) != "undefined" && 
            img.getAttribute("enableRolloverImages") != null)
        {
            if (img.getAttribute("enableRolloverImages").toLowerCase() == 'true')
            {
                // preload the 'On' image
                var preImage = new Image();
                preImage.src = img.getAttribute("rolloverImageSrcOn");
                preloadedRolloverImages[j] = preImage;
                j++;
 
                // assign event handlers
                img.onmouseover = function() { this.src = this.getAttribute("rolloverImageSrcOn") }; 
                img.onmouseout = function() { this.src = this.getAttribute("rolloverImageSrcOff") }; 
            }
        }
    }
}
notes/javascript/rolloverimages.txt · Last modified: 2016/12/14 by admin