Reputation: 87
Currently it repeats the same images twice before transitioning. It seems like it's not incrementing through 'i'. How can I fix the jQuery so that it only shows each image once at a time?
Here's the fiddle: http://jsfiddle.net/9DU5M/
$(function () {
var i = 1;
(function doAnimation() {
$('.slide' + i + '-img').css({ 'background-position-x': '-50px', opacity: 1 }).animate({ 'background-position-x': '-5px' }, 5000, 'linear').animate({ 'background-position-x': '0px', opacity: 0 }, 500, 'linear', function () {
$(this).attr('class', 'slide' + (i = i == 3 ? 1 : i + 1) + '-img').css({ 'background-position-x': '-50px', opacity: 1 }).animate({ 'background-position-x': '-5px' }, 5000, 'linear').animate({ 'background-position-x': '0px', opacity: 0 }, 500, 'linear', doAnimation);
});
})();
});
Upvotes: 0
Views: 228
Reputation: 237
You have run the animation twice inside your loop.. Also, your condition statement in the last animation was late in checking..
I have tested this and it animates smoothly as desired same in your own fiddle...
$(function () {
var i = 1;
(function doAnimation() {
$('.slide' + i + '-img').css({
'background-position-x': '-50px',
opacity: 1
}).animate({
'background-position-x': '-5px'
}, 5000,
'linear')
.animate({
'background-position-x': '0px',
opacity: 0 }
, 500,
'linear', function () {
$(this).attr('class', 'slide' + (i = ((i+1) > 3) ? 1 : i + 1) + '-img');
doAnimation();
});
})();
});
Upvotes: 1
Reputation: 700342
When you have changed to the new image, you are showing it and then fading it out before you go back to showing it again. Just fade it in and go back to showing it:
$(function () {
var i = 1;
(function doAnimation() {
$('.slide' + i + '-img').css({
'background-position-x': '-50px',
opacity: 1
}).animate({
'background-position-x': '-5px'
}, 5000, 'linear').animate({
'background-position-x': '0px',
opacity: 0
}, 500, 'linear', function () {
$(this).attr('class', 'slide' + (i = i == 3 ? 1 : i + 1) + '-img').animate({
'background-position-x': '0px',
opacity: 1
}, 500, 'linear', doAnimation);
});
})();
});
Demo: http://jsfiddle.net/Guffa/9DU5M/1/
Note: I'm not sure what you are trying to do with the background position. The background-position-x
style is non-standard, and only exist in IE and Webkit browsers (Safari). You need to use the background-position
style to make it work in more browsers.
Upvotes: 1