Search code examples
jqueryhtmlfadeinfadeout

jQuery Fade in / Fade out divs with variable timing


I'm trying to modify a solution already on here but to have a total of 7 divs that fade in/out using the same space on the page. And then loop back to the first div to start again.

I also need to have variable timings, i.e. div one stays visible for 5 seconds, div two stays visible for 3 second, div three for 4 seconds and so on as it depends how much content each has.

I just can't seem to be able to successfully add a third div that fades in after div two (red one).

Code I am trying to modify:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

    <script>
$(document).ready(function() {
   $('#one').delay(3000).fadeOut(100);
   $('#two').delay(3000).fadeIn(100);
 });
</script>

<style>
html, body {background-color: yellow}
#one {
  width: 300px;
  height: 300px;
  position: absolute;
  top: 5px;
  left: 5px;
  z-index: 200;
  background-color: #00f;
  cursor: pointer;
}

#two {
  width: 300px;
  height: 300px;
  position: absolute;
  top: 5px;
  left: 5px;
  z-index: 100;
  background-color: #f00;
  display: none;
}
</style>

<div id="one">Content for Div one to go here</div>
<div id="two">Content for Div two to go here</div>

Any help would be much appreciated. Thanks.


Solution

  • If you need a fadein/fadeout loop you can do something like this:

    $(document).ready(function() {
    
    loopbox();
    
    function loopbox() {
        $('#one').fadeIn(100).delay(5000).fadeOut(100, function() {
          $('#two').fadeIn(100).delay(3000).fadeOut(100, function() {
            $('#three').fadeIn(100).delay(4000).fadeOut(100,function() {                                
            loopbox();
            });
          });
        });
      }
    });
    

    you can add as many divs you need in this callback function and choose different timing for each one.

    Here's the jsfiddle