Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fade in divs one after another

Hey there guys, Im good with HTML and CSS but have only jsut started to scratch the surface of jQuery. I'm looking to make 3 divs fade in on page load one after another. So far I have this

<script type="text/javascript">
    $('#1').hide().fadeIn(1500);
    $('#2').hide().fadeIn(1500);
    $('#3').hide().fadeIn(1500);
</script>

I heard that to use css to set the display to none is a nightmare for anyone with a non JavaScript browser so I used the hide function to initially hide the divs.

But this only fades them in all at once. Any ideas?

like image 678
Alex Sadler Avatar asked Nov 26 '25 15:11

Alex Sadler


2 Answers

You can .delay() each so the one before fades in at the right time, for example:

$("#1, #2, #3").hide().each(function(i) {
  $(this).delay(i*1500).fadeIn(1500);
});

This fades them in...in the same order they occur in the page which is usually what you're after, the first is delayed 0 so it's instant, the second is delayed 1500ms (so when the first finishes, etc). In the .each() callback i is the index, starting with 0 so you can use that to quickly calculate the right delay here.

Another advantage here is this approach is much easier to maintain, give them a class for example then you can just do:

$(".fadeMe").hide().each(function(i) {
  $(this).delay(i*1500).fadeIn(1500);
});

Then you require zero maintenance on the JavaScript side to add additional <div> elements to fade.

like image 69
Nick Craver Avatar answered Nov 29 '25 05:11

Nick Craver


The fade in command contains a call back function, see documentation. This means you could chain the events.

<script type="text/javascript">
    $('#1, #2, #3').hide();

   $('#1').fadeIn(1500, function(){ $('#2').fadeIn(1500, function(){$('#2').fadeIn(1500)})});
</script>
like image 28
Paul Hadfield Avatar answered Nov 29 '25 03:11

Paul Hadfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!