user979331
user979331

Reputation: 11961

Jquery display divs on loop one at a time and fade

I have these 5 divs:

<div id="content-1"></div>
<div id="content-2"></div>
<div id="content-3"></div>
<div id="content-4"></div>
<div id="content-5"></div>

and what I am trying to is the following, start off by displaying the first div, after 30 seconds, fade that div out and content-2 in and after 30 seconds, fade content-2 out and content-3 in and so on, once it has reached the end, start back at 1.

This is what I got started on, right now content-1 will start and after 5 seconds it will disappear and content-2 will appear, there has just gotta be a better way and there is no way to tell when it gets to 4 and starts at 1 again.

$('#content-1').show(0).delay(5000).hide(0);
$('#content-2').hide(0).delay(5000).show(0);

I hope this makes sense, any help would be appreciated.

Thanks,

Upvotes: 0

Views: 987

Answers (2)

Gene Kelly
Gene Kelly

Reputation: 199

Not the most efficient way but it works and is easy to understand. This code will loop through a set of elements fading them in and out one at a time.

<script>
$(document).ready(function() {

	var timer = setInterval( showDiv, 5000);
	var start = $('.slideshow > img').first();

	function showDiv() {
		start.fadeOut(function(){ 
			if(start.next().length==0) {
				start=$('.slideshow > img').first();
				$('.slideshow > img').first().fadeIn(); 	
			} else {
				start.next().fadeIn();
				start=start.next();
			}
		});
	}
});
</script>
<style>
.slideshow img { display: none; }
</style>
<div class="slideshow">
  <img class="slides1" src="slide_1.jpg" alt="" style="display: block;" />
  <img class="slides2" src="slide_2.jpg" alt="" />
  <img class="slides3" src="slide_3.jpg" alt="" />
  <img class="slides4" src="slide_4.jpg" alt="" />
</div>

Upvotes: 0

Riad
Riad

Reputation: 3870

You can do this easily with Jquery Timing

HTML:

<div id="content-1" class="content"></div>
<div id="content-2" class="content"></div>
<div id="content-3" class="content"></div>
<div id="content-4" class="content"></div>
<div id="content-5" class="content"></div>

JS:

var divs = $('.content').hide();
divs.each($).fadeIn(1000).not(divs.last()).delay(5000).fadeOut(1000,$);

Upvotes: 1

Related Questions