views:

201

answers:

3

Hi there,

I am attempting to fade in a set of divs, one after another. I thought I could use the simple For Each function that jquery offers. My code is as follows:

$('#menu_activate').click(function(){
  $('div.section').each(function(i){
    $(this).fadeToggle();     
  });
});

The good thing about this is that it does iterate through the divs and they all fade in when I click the activate button. The problem is that there is NO DELAY between the elements fading in.

Any ideas? I tried the timeout function to no avail...

Also, fadeToggle is a custom jquery function that works as you would expect.

Thanks in advance. Tom.

A: 
$('#menu_activate').click(function(){
    $('div.section').each(function(i){
        $(this).queue(function() {
            $(this).fadeToggle();
            $(this).dequeue();
        });
    });
});
chaos
+2  A: 

You probably want the setTimeout, and you want the timeout to increment with each div. The issue here is that the fadeToggles are all being called right after one another, with no delay. Therefore, you have to introduce a delay yourself. There's a couple of ways you can do this, here's one:

var myTimeout = 0;
var myIncrement = 300; // Wait 300ms between each div
$('#menu_activate').click(function(){
  $('div.section').each(function(i){
    setTimeout(function() { $(this).fadeToggle() },myTimeout);
    myTimeout += myIncrement;     
  });
});

Basically set the fadeToggles to happen after a timeout which increments with each div.

Adam Bellaire
+1 from me - elegant
Dominic Rodger
Thankyou! Very elegant. I had to tweak it a little bit to get it to work, but you sent me in the right direction. Thanks
Tisch
A: 

Final answer!

  var myTimeout = 0;
  var myIncrement = 300; // Wait 300ms between each div
  $('#menu_activate').click(function(){
    $('div.section').each(function(i){
      setTimeout(function() { $('#section_'+i).show(); },myTimeout);
      myTimeout += myIncrement;     
    });
  });

It was the increment that I wasn't thinking about when I did it... and with Adam's answer, it wasn't referring to the DIV's with "this" so I had to give them individual ID's and iterate on that instead. So close Adam. Very impressive and thankyou for being so helpful!

Tisch