Reputation: 4696
I was just playing around jQuery animate(). I tried to make an infinte scrolling background of sorts (fiddle here). But for the life of me I can't figure out a smooth transition. Code posted here -
HTML
<div class='bg r hide'></div>
<div class='bg g hide'></div>
<div class='bg y hide'></div>
<div class='bg b hide'></div>
JavaScript
var backgroundTimeout = 1700;
function animateMotion(){
$('.bg').each(function(i, item) {
var self = $(this);
setTimeout(function() {
self.css('opacity', '0.5').removeClass('hide')
.animate({opacity: 1, marginLeft: '+=6'}, backgroundTimeout / 3)
.animate({
marginLeft: '+=30',
opacity: 0,
queue: false,
}, backgroundTimeout + 400, 'linear', function() {
self.css('marginLeft', 0);
self.css('opacity', 1);
self.addClass('hide');
})
if (self.index() === $('.bg').length - 1) {
setTimeout(animateMotion, backgroundTimeout);
}
}, backgroundTimeout * i + 1)
});
}
What I'm going for - 1st div moves out - fades to nothing - halfway through fadeout - next div fades in and starts the cycle again. Any ideas where I'm going wrong?
Upvotes: 1
Views: 1047
Reputation: 54649
Not sure if this is where you're aiming at, but have a look:
(function loop(idx) {
var
$elements = $('#wrapper div'),
idx = idx % $elements.length;
$elements.eq(idx).css({
opacity: 0,
left: 0
}).removeClass('hide').show().animate({
opacity: 1,
left: 30
}, {
duration: 1000,
easing: 'linear',
complete: function () {
$(this).animate({
opacity: 0,
left: 60
}, {
duration: 1000,
easing: 'linear',
complete: function () {
$(this).addClass('hide');
}
});
loop(idx + 1);
}
});
}(0));
with:
<div id="wrapper">
<div class='bg r hide'></div>
<div class='bg g hide'></div>
<div class='bg y hide'></div>
<div class='bg b hide'></div>
</div>
demo: http://jsfiddle.net/hbh7z/1/
Upvotes: 3