Easiest way to animate a background image sliding to the left?

What's the best way to animate a background image sliding to the left and looping? Let's say I have a progress bar with a background that I want to animate when it is active (for example, in Gnome or OS X).

I have been playing around with the $ (...) function. animate () and trying to change the corresponding CSS property, but I keep hitting the brick wall trying to figure out how to change the background position of the property. I can't just increase its value, and I'm not sure if this is even the best approach.

Any help is appreciated!

+1


source to share


4 answers


Once I posted this I figured it out. In case it helps anyone else, here's the function I ran into:



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);
    });
}

      

+15


source


Just a suggestion, but instead of using a standard function and passing an 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 call the function like this:

$(this).animateBar(); 

      



vs

 animateBar( $(this) );

      

Just my 2 cents. However, @Markus Gif's solutions are definitely superior unless you have a specific reason to use a jQuery animated image. Also, your solution won't work on its own.

+3


source


I would say the best solution in your case (animation of the progress bar) is to use an animated .gif as the background of the background image.

Also, to switch from a static progress bar to an animated one, just use something like:

$("#progress").css("background-image", "progress.gif");

      

+1


source


You can use the Spritely plugin , and for your case of animating a sliding background and repeating it, you can use panning () which constantly moves the background image left or right and then repeats.

0


source







All Articles