What's the best way to animate a background image sliding to the left, and looping it? Say I've got a progress bar with a background I want to animate when it's active (like in Gnome or OS X).
I've been playing with the $(...).animate()
function and trying to modify the relevant CSS property, but I keep hitting a brick wall when trying to figure out how to modify the background-position
property. I can't just increment its value, and I'm not sure if this is even the best approach.
Any help appreciated!
What's the best way to animate a background image sliding to the left, and looping it? Say I've got a progress bar with a background I want to animate when it's active (like in Gnome or OS X).
I've been playing with the $(...).animate()
function and trying to modify the relevant CSS property, but I keep hitting a brick wall when trying to figure out how to modify the background-position
property. I can't just increment its value, and I'm not sure if this is even the best approach.
Any help appreciated!
Share Improve this question edited Sep 14, 2018 at 9:01 Aliaksandr Sushkevich 12.4k8 gold badges40 silver badges46 bronze badges asked Dec 14, 2008 at 21:39 WilcoWilco 33.4k49 gold badges132 silver badges161 bronze badges4 Answers
Reset to default 15As soon as I posted this I figured it out. In case it helps anyone else, here's the function I came up with:
function animateBar(self) {
// Setup
var bar = self.element.find('.ui-progress-bar');
bar.css('background-position', '0px 0px');
bar.animate({
backgroundPosition: '-20px 0px'
}, 1000, 'linear', function() {
animateBar(self);
});
}
Just a suggestion, but rather than using a standard function and passing in the element as an argument, it would be better to use fn.extend.
$.fn.extend({
animateBar: function(){
$(this).find('.ui-progress-bar').css('background-position', '0px 0px');
$(this).find('.ui-progress-bar').animate({
backgroundPosition: '-20px 0px'
}, 1000, 'linear', function() {
animateBar(self);
});
}
});
Then you would call the function like this:
$(this).animateBar();
vs
animateBar( $(this) );
Just my 2 cents. However @Markus 's Gif solutions is definitely superior, unless you have a specific reason to use an image animated by jQuery. Also your solution will not loop on its own.
I'd say a better solution in your case (animating a progress bar) is to use an animated .gif as the progress bar's background-image.
Also, to switch from a static progress bar to an animated one, just use something like:
$("#progress").css("background-image", "progress.gif");
You can use the Spritely plugin , and for your case of animating a sliding background and repeating it, you can use the pan() method which makes the background image pan continually to the left or right and then repeat.