Reputation: 45
I have an array like:
var txt = new Array('1st', '2nd', '3rd');
I need to put this array into a loop, apply each text to a (common) div, show it with an animation, then hide it with another animation.
What I have done is, first added an html div:
<div id="contentHolder"></div>
Then in my jQuery code, I wrote:
$.each(txt, function(index, value)) {
$("#contentHolder").empty().append(value).slideDown('slow').fadeOut('slow');
}
What I get is that the contentHolder div is filled with the "3rd" and it appears and disappears for three times! It looks like the text is being applied in the loop and when it's done, the queue of animations is being run.
Here is its code: http://jsfiddle.net/fbgp2000/97ThY/2/
What I need is the same but showing different texts in each loop.
Could anyone please tell me what I'm missing?
Upvotes: 2
Views: 1968
Reputation: 67207
You have to use recurion and call backs
in this context, since .animate()
is asynchronous
.
Try this,
var txt = new Array("1st", "2nd", "3rd");
var xCnt = -1;
function AnimateOneByOne()
{
xCnt += 1;
if( xCnt < txt.length){
$("#contentHolder")
.empty()
.append(txt[xCnt])
.slideDown('slow')
.fadeOut('slow', AnimateOneByOne);
}
}
AnimateOneByOne();
Upvotes: 2
Reputation: 144709
You should use callback function here, which is called when the animation is complete, your loop runs much faster than the animations:
var $contentHolder = $('#contentHolder');
(function worm(i) {
$contentHolder.fadeOut(function() {
$(this).text( txt[i] ).slideDown(function() {
txt.length !== ++i ? worm(i) : '_the end';
});
});
})(0);
For restarting:
worm( txt.length !== ++i ? i : 0 );
Upvotes: 1
Reputation: 16055
A rather simple solution
var txt = new Array('1st', '2nd', '3rd'),
item = 0,
t = setInterval(function(){
$("#contentHolder").html(txt[item]).slideDown(1000).fadeOut(1000);
item++;
if(item>txt.length){
clearInterval(t);
item = 0; // for further use;
}
}, 2000);
Upvotes: 1