Help with opacity fadd in effect on image

I’ve created a slide show out of HTML and CSS but I’m trying to add an opacity effect so that when the link is clicked the image fades in from nothing.

At the moment on click the image fades to zero straight away;


window.onload = initAll;

function initAll () {
	
	document.getElementById("slide-one-nav").onclick = fadeInTimer;
	
}

function fadeIn() {

for ($z = 0; $z < 10; ++$z) {

	transImg($z);
	break;
}
}

function transImg($value) {
	
	//document.getElementById("slide-one").style.opacity = $value/10;
	document.getElementById("slide-one").style.filter = 'alpha(opacity=' + $value*10 + ')';
	//alert("The opacity has changed");
	
}

function fadeInTimer(){

for($i = 0; $i < 1000; $i++) {
	
	setTimeout(fadeIn,$i * 100);
	break;
}

}

Here are three common approaches to doing fade-ins:

  1. Using a for-loop with setTimeout
  2. Using recursive setTimout calls
  3. Using setInterval

You are using the first way, but those compounded for-loops are a problem.
Also, those break statements are just halting everything.
Try simplifying it to the following:

window.onload = initAll;

function initAll () {
  document.getElementById("slide-one-nav").onclick = fadeIn;
}

function transImg($value) {
  document.getElementById("slide-one").style.opacity = $value/100;
  document.getElementById("slide-one").style.filter = 'alpha(opacity=' + $value + ')';
}

function fadeIn(){
  for(var $i = 0; $i <= 100; $i++) {
    setTimeout('transImg(' + $i + ')', $i * 40);
  }
}

That way does generate a large series of setTimeouts, and each has to parse the function expression to allow the $i arguement to be included. Here’s the 3rd way using setInterval, which is generally more efficient - amend the fadeIn as follows:

var fader = null;

function fadeIn(){
  var $i = 0;
  fader = setInterval(function() {
    if ($i++ >= 100) clearInterval(fader);
    else transImg($i);
  }, 40);
}