JavaScript: Slowly Fade Using Opacity

The JavaScript Fade Anything Technique is great for fading a specified background color of an element back to its native color, but I wanted to dissolve an entire div, including one with images, which the current version of the Fade Anything method doesn’t allow for. After an unsuccessful search for something to suit my needs, I built my own.

Include the reference to the JavaScript file in the header of your HTML. Surround whatever you want to fade with a div tag. Apply an onclick or onmouseover method to run "javascript:slowly.fade('whatever');", making sure to assign an id to the div tag to match (i.e. id="whatever").

var opacity = 96; // Avoid starting at 100% due to Mozilla bug
var slowly = {
  fade : function (id) {
    this.fadeLoop(id, opacity);
  },
  fadeLoop : function (id, opacity) {
    var o = document.getElementById(id);
    if (opacity >= 5) {
      slowly.setOpacity(o, opacity);
      opacity -= 4;
      window.setTimeout("slowly.fadeLoop('"+id+"', "+opacity+")", 50);
    } else {
      o.style.display = "none";
    }
  },
  setOpacity : function (o, opacity) {
    o.style.filter = "alpha(style=0,opacity:" + opacity + ")";  // IE
    o.style.KHTMLOpacity = opacity / 100;           // Konqueror
    o.style.MozOpacity = opacity / 100;	            // Mozilla (old)
    o.style.opacity = opacity / 100;                // Mozilla (new)
  }
}

Works in IE6+, Firefox 1.5+, Chrome.

Save your own copy of the SlowlyFade file — do not steal my bandwidth, please!

As always, this script is provided as-is, without any warranty of any kind, express, implied or otherwise, including without limitation, any warranty of merchantability or fitness for a particular purpose. In no event shall I be liable for any special, incidental, consequential or indirect damages of any kind, or any damages whatsoever resulting from loss of; use, data or profits, whether or not advised of the possibility of damage, and on any theory of liability, arising out of or in connection with the use or performance of this script.

Click anywhere in this box to get rid of this annoying status message. This is a working demonstration of how the SlowlyFade function works.