Tutorial: How does image fade in when picture loaded in JavaScript

There is a very nice method mention in here by Richard Rutter. But i will explain it with my own words on how this is being done since i am curious on how some of these things work. i basically look it up and explain them so that i could understand them in the future if needed.


#photoholder {
  background:#fff url('loading.gif') 50% 50% no-repeat;
#thephoto {

document.write("<style type='text/css'> #thephoto {visibility:hidden;} </style>");
window.onload = function() {initImage()}
function initImage() {
  imageId = 'thephoto';
  image = document.getElementById(imageId);
  setOpacity(image, 0);
  image.style.visibility = 'visible';
function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;

  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";

  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;

  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;

  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
function fadeIn(objId,opacity) {
  if (document.getElementById) {
    obj = document.getElementById(objId);
    if (opacity <= 100) {
      setOpacity(obj, opacity);
      opacity += 10;
      window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100);


<div id='photoholder'>
<img src='cute-puppy.jpg' alt='Photo' id='thephoto' />

the code above is the whole HTML file that is needed for this explanation. I did not change anything written by Richard Rutter and merely just compile it up for my explanation.

So what is going on with the above code is that Richard has written a very unique function for each activity occurs in this example. There are basically 3 method, initImage(), setOpacity, fadeIn. The css in here doesn't really play any important round other than displaying the image up. The initImage method set the oject opacity and activate fadeIn method that did a recursive to slowly fade the image. The technique to Richard way of doing is to load the 'loading' image out to the guys and only started fading the image once it has been loaded  by using the onload function to determine whether the page has completely loaded. Once it is determine, it will active the fade in method to do the trick.

The main interest i have is how fade in effect works and with the code written by Richard, it is clearly understandable how this is happening.

You can look at the example HERE.