tags:

views:

64

answers:

2
for(i=100;i>=0;i--){
    icon.style.filter="alpha(opacity=0)";
}

this is my for loop ... wat i want is tat each time for loop completes 1 loop it should wait or sleep for 100millisec so tat it can give a fadding effect....

+4  A: 

You should call setTimeout, which will execute a function after a given delay.

For example:

function fadeOut(i) {
    i = i || 100;
    icon.style.filter  = "alpha(opacity=" + i + ")";
    icon.style.opacity = i / 100;

    i--;
    if (i > 0)
        setTimeout(function() { fadeOut(i) }, 100);    //Call fadeOut in 100 milliseconds
}

You can also call setInterval, which will keep calling the function until you call clearInterval.
For example:

function fadeOut() {
    var i = 100;
    var timer = setInterval(function() {
        icon.style.filter  = "alpha(opacity=" + i + ")";
        icon.style.opacity = i / 100;
        i--;
        if (i <= 0)
            clearInterval(timer);
    }, 100);
}

You can do this much more easily using the jQuery library, like this:

$(icon).fadeOut();
SLaks
+1 The only sane solution.
middaparka
or setInterval if many times called. Then use clearInterval
Alexander
i hv used it bt doesn't work properly... can u gv me proper way to write it... i had wrttn it sa below..for(i=100;i>=0;i--){ //icon.style.filter="alpha(opacity=0)"; setTimeOut("fade2()",120) }it is fine.....
suraj
You should pass a function to `setTimeout`, not a string. Your code will call `setTimeout` 100 times in a row, so that every callback will fire at the same time 120ms later.
SLaks
Use my example.
SLaks
setTimeOut("fade2()",120) is the same as setTimeOut(fade2,120) and setTimeOut(function(){fade2();}),120). You can call it different ways.
A: 

John Resig wrote very cool JavaScript functions for fading in and out (Editing slightly):

function fadeOut(elem, time)
{

 var t = time / 100;

 var c = 0;

 for (var b = 100; b >= 0; b -= 5)
 {

  c +=5;

  (function(){
   var pos = b;

   setTimeout(function(){

    setOpacity(elem, pos);
   }, ((c + 1) * t));
  })();
 }

}

function fadeOut(elem, time)
{
 show(elem);

 var t = time / 100;

 var c = 0;

 for (var b = 100; b >= 0; b -= 5)
 {

  c +=5;

  (function(){
   var pos = b;

   setTimeout(function(){

    setOpacity(elem, pos);
   }, ((c + 1) * t));
  })();
 }

}

function show(elem)
{

 elem.style.display = '';
}

function setOpacity(elem, level)
{
 if (elem.filters)
 {
  elem.style.filters = 'alpha(opacity=' + level + ')';
 }
 else
 {
  elem.style.opacity = level / 100;
 }
}

You would then use it like:

var el = document.getElementById("#element");

fadeIn(el,1000); //Fade in over 1 second
fadeOut(el,1000); //Fade out over 1 second

EDIT:

Would be easier with jQuery, but you would learn how it works using normal JavaScript

$("#element").fadeOut();
$("#element").fadeIn();