Let's say I have the following divs:
<div class="a">You are funny.</div>
<div class="b">You are smart.</div>
<div class="c">You are cool.</div>
What is the best way to show div.a
for 5 seconds, then fade out and fade in div.b
for 5 seconds and then to div.c
and then back to div.a
and continue looping for an infinite amount of time?
Thanks :)
Let's say I have the following divs:
<div class="a">You are funny.</div>
<div class="b">You are smart.</div>
<div class="c">You are cool.</div>
What is the best way to show div.a
for 5 seconds, then fade out and fade in div.b
for 5 seconds and then to div.c
and then back to div.a
and continue looping for an infinite amount of time?
Thanks :)
Share Improve this question edited Apr 24, 2011 at 4:57 stewart715 asked Apr 24, 2011 at 4:44 stewart715stewart715 5,63711 gold badges49 silver badges81 bronze badges2 Answers
Reset to default 5You can use an array of values and loop thru them.
var div = $('div').hide(),
news = ['news1', 'news2', 'news3'],
count = 0;
function changeNews() {
div.fadeIn().delay(500).fadeOut(function() {
changeNews();
}).text(news[count++])
if (count == news.length) {
count = 0;
}
}
changeNews();
Check working example at http://jsfiddle/qJa3h/
How about a jQuery plugin? I haven't tested it but something like this should get you started:
(function($) {
$.fn.keepFadingToNext = function(options) {
var defaults = {
duration: 5000
};
var settings = $.extend({}, defaults, options);
var original = this;
var doAnimations = function(element) {
element.fadeIn(settings.duration, function() {
element.fadeOut(settings.duration, function() {
var next = element.next();
if (next.length === 0) {
next = original;
}
doAnimations(next);
});
});
};
doAnimations(original);
return original;
};
})(jQuery)
$('.a').keepFadingToNext();
// or
$('.a').keepFadingToNext({ duration: 3000 });