views:

28

answers:

2

JS:

$(function(){
 chainAnim('.section','slow','1')  });
 function chainAnim(e,s,o) {
        var $fade = $(e);
        var code = "console.log('Done.');";
        $fade.each(function(){
   code = "$('#"+$(this).attr('id')+"').fadeTo('"+s+"','"+o+"',function(){"+code+"});";
        });
        eval(code);
}

HTML:

 <div id="wrapper">
  <div class="section" id="section-1">Section 1</div>
  <div class="section" id="section-2">Section 2</div>
  <div class="section" id="section-3">Section 3</div>
  <div class="section" id="section-4">Section 4</div>
 </div>

When animating,section 4 is animated in first. How can I reverse this?

A: 

Of course section 4 is animated first, because "code" is set to the last one in the loop ;)

Code gets overwritten in every loop cycle, you should use += instead of = in the loop.

Anyway, your approach isn't best practice, check this out:

Edit: Recursive Fade!

$(document).ready(function() {
 chainAnim($('.section'), 'slow', 1);
});

function chainAnim(e, s, o) {
  e = $.makeArray(e);
  if(e.length == 0) { return; }
  $(e.shift()).fadeTo(s, o, function() {
    console.log('Done.');
    chainAnim(e, s, o);
  });
}

Demo: http://jsfiddle.net/97dEc/3/

sled
Thanks a lot sled for the help!I tried what you gave me but it all fades in at the same time.
Tom Fletcher
hi, sorry for that I added a new version which is independent from the speed you use for fading.
sled
sled - Just thought I'd give you heads up that the demo is different from your answer. You probably just forgot to click "Fork" or "Update" before copying the URL. :o)
patrick dw
thanks, I got it fixed ;)
sled
+2  A: 

This should do what you want, but I got rid of your eval() code. Not sure why you were taking that approach.

Example: http://jsfiddle.net/wqWE5/

I also changed the second argument from "slow" to 800 so it could be used in the .delay().

The duration you pass multiplied by the current index of the .each() will make the animation happen in sequence.

$(function(){
     chainAnim('.section',800,'1');
});

function chainAnim(e,s,o) {
        var $fade = $(e);
        var code = function() {console.log('Done.');};
        $fade.each(function( i ){
            $(this).delay(i * s).fadeTo(s,o,code);
        });
} 
patrick dw
I think this did the trick. Thanks a lot Patrick!
Tom Fletcher
@Tom - You're welcome. :o)
patrick dw
@Tom - If this answer helped you, please mark it as the answer (click the checkmark underneath the voting buttons). That ensures others know that this is the answer and that patrick receives points for helping you. Thanks!
JasCav
Thanks JasCav, how can I checkmark this whole site? I love it. Everyone is so helpful.
Tom Fletcher