Reputation: 1241
I'm wondering how to make infinite animation on jquery with a plugin "background position animation" i tried to implement setInterval(); but it didn't work, there a jsfiddle.
You can see js code like
$('#tile').css({backgroundPosition:'0px 0px'});
function infinite(){
$('#tile').animate({backgroundPosition:"-5000px -2500px"},12000);
}
infinite();
setInterval(infinite,12000);
Can anyone help me?
Thanks!
Upvotes: 2
Views: 9140
Reputation: 3694
This maybe a late answer, but below is a function that doesn't required the background position plugin.
var animate = $('#element');
function loopbackground() {
animate.css('background-position', '0px 0px');
$({position_x: 0, position_y: 0}).animate({position_x: -5000, position_y: -2500}, {
duration: 12000,
easing: 'linear',
step: function() {
animate.css('background-position', this.position_x+'px '+this.position_y+'px');
},
complete: function() {
loopbackground();
}
});
}
loopbackground();
View a working demo here: http://jsfiddle.net/kusg5mdg/
Edit....
I'm back 4 years later to turn the above function into a more reusable bit of code (because why not? ¯\_(ツ)_/¯ )
Reusable, jQuery namespaced function:
$.fn.loopBackground = function(options = {}) {
options = $.extend({
x: 0,
y: 0,
duration: 300,
easing: 'linear'
}, options);
var $this = $(this);
function loop() {
$this.css('background-position', '0px 0px');
$({ x: 0, y: 0 }).animate({ x: options.x, y: options.y }, {
duration: options.duration,
easing: options.easing,
step: function() {
$this.css('background-position', this.x+'px '+this.y+'px');
},
complete: function() {
loop();
}
})
}
loop();
};
Usage:
$('#title').loopBackground({
x: -5000,
y: -2500,
duration: 30000,
easing: 'linear' // Optional https://jqueryui.com/easing/
});
Working example here: http://jsfiddle.net/dmvpu06f/
Upvotes: 3
Reputation: 1612
or you can use this:
function infinite(){
$('#tile').css({backgroundPosition:'0px 0px'}).animate({backgroundPosition:"-5000px -2500px"},12000, infinite);
}
infinite();
Upvotes: 4
Reputation: 206343
You have to reset your background initial position after the animation is over inside the animation callback.
$('#tile').css({backgroundPosition:'0px 0px'});
var to;
function infinite(){
to = setTimeout(function(){
$('#tile').animate({backgroundPosition:"-5000px -2500px"},12000,function(){
$('#tile').css({backgroundPosition:'0px 0px'});
infinite();
});
});
}
infinite();
Or your way: but I had time ago bad issues using setInterval - causing animations buildups on tab inactivity, but I think this issue is removed from jQuery version 1.6.
Here you go:
$('#tile').css({backgroundPosition:'0px 0px'});
function infinite(){
$('#tile').animate({backgroundPosition:"-5000px -2500px"},12000,function(){
$(this).css({backgroundPosition:'0px 0px'});
});
}
infinite();
setInterval(infinite,12000);
Upvotes: 2