Reputation: 3098
Have this HTML
<span style="display:none">slogan 1</span>
<span style="display:none">slogan 2</span>
<span style="display:none">slogan 3</span>
Have this JS:
var timer = 0;
$('.banner').children('span').each(function(index) {
timer = timer + 2000;
$(this).delay(2500*index).fadeIn(timer, 'linear').fadeOut('3000', 'linear');
});
JS basically cycles through each span fading them in and out. But it does it only ONCE (from slogan 1 to slogan 3). I want to somehow cycle spans as many times as I want. for(){} does it improper ways.
Could you help me in this? Thanks.
Upvotes: 1
Views: 221
Reputation: 54659
(function fade(num, idx, cycles) {
var
spans = $('span'),
idx = idx || 0, idx = idx < spans.length ? idx : 0,
cycles = typeof cycles === 'undefined' ? num * spans.length : cycles;
if (cycles > 0) {
spans.eq(idx).fadeIn().fadeOut(function () {
fade(num, idx + 1, cycles - 1);
});
}
}(2 /* two runs total*/));
Upvotes: 2
Reputation: 50039
This should work for you - http://jsfiddle.net/ML5b5/1/
<span>slogan 1</span>
<span style="display:none">slogan 2</span>
<span style="display:none">slogan 3</span>
var spanCounter = 0;
setInterval(function(){
var $span = $('span').eq(spanCounter);
spanCounter = cycleSpan($span, spanCounter);
spanCounter = (spanCounter >= $('span').length) ? 0 : spanCounter;
}, 3000)
function cycleSpan($span, spanCounter) {
$span.fadeOut('slow', function(){
if ($span.next('span').length) {
$span.next().fadeIn('slow');
} else {
$span.siblings('span:first').fadeIn();
}
});
return ++spanCounter;
};
This uses a counter variable in the global scope, which I don't really like, but you could try refactoring it to take it out. This code essentially loops through the spans and sends it to a cycle function which will hide the current span and show the next one. You might want to update these spans with a class so they don't mess up the rest of your documents.
Upvotes: 0