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's my jsfiddle demo.
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!
or you can use this:
function infinite(){
$('#tile').css({backgroundPosition:'0px 0px'}).animate({backgroundPosition:"-5000px -2500px"},12000, infinite);
}
infinite();
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With