Reputation: 6415
I've got a DOM element
that contains a variable number paragraphs:
<section id="paragraphs">
<p>Here's a paragraph</p>
<p>Here's another one</p>
<p>Here's the third</p>
</section>
These p
elements are hidden with display:none;
in my CSS.
What I want to do is fade in the first paragraph, fade it out after a set amount of time (say 10 seconds).
Once the first paragraph has faded out - I want to show the second paragraph in the same manner (fade in, wait 10 seconds, fade out).
This should repeat for each paragraph (returning to the first paragraph and continuing when it's gone through them all).
Here's the JavaScript that I've got (I've tried a few things - all with the same result as this):
// count paragraphs
var numberOfParagraphs = $('#paragraphs').children.length;
var x = 1;
while (x<=numberOfTestimonials) {
$(".testimonials p:nth-child("+ x + ")").fadeIn().delay(10000).fadeOut();
x++;
}
The problem is that all of the paragraphs are fading in at the same time (on page load) - when I only want to fade them in/out one at a time.
Any help is appreciated.
Upvotes: 0
Views: 96
Reputation: 207901
Here's a solution using a recursive function that rotates the elements and fades the one that is first (I'm using three seconds instead of ten to make it easier to see the effect):
$('#paragraphs p').hide();
doFade('#paragraphs p:first');
function doFade(elem) {
$(elem).fadeIn(250).delay(3000).fadeOut(250, function () {
$(this).insertAfter($('#paragraphs p:last'));
doFade('#paragraphs p:first');
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section id="paragraphs">
<p>Here's a paragraph</p>
<p>Here's another one</p>
<p>Here's the third</p>
</section>
Upvotes: 1