0

I'm trying to animating the background-position of an element using jQuery's .animate() method. The background-position attribute is set by defining both the x and y values, like so:

background-position: 100px 100px;

Webkit now supports a background-position-x and background-position-y, but it is not yet supported in Firefox. If I animate only one value —

eg. $(div).animate({'background-position':'200px'}, 1000); — it automatically animated the X value and not the way. I can't find a way to animate the the Y value independently.

Is it a matter of getting the syntax right? Some trick with concatenation?

Note: I did get this to work in webkit using background-position-y, but would like FF support as well.

Deadlock
  • 1,575
  • 1
  • 19
  • 34
KeenanC
  • 33
  • 5

2 Answers2

0

Simply use the following:

background-position:0 200px;

Where 0 is x and 200 is y:

background-position:x y;
bukka
  • 4,973
  • 3
  • 19
  • 21
  • multiple values in animate doesn't seem to work: http://jsfiddle.net/qhqnd/ there seem to be an explanation in the question I linked in the comment above – Andrea Casaccia Mar 23 '13 at 17:23
0

I believe this requires a jQuery extension. It's a bit bulky, but here's a working example

/**
 * @author Alexander Farkas
 * v. 1.02
 *
 * Edited by Nelson Wells for jQuery 1.8 compatibility
 */
(function($) {
    $.extend($.fx.step,{
        backgroundPosition: function(fx) {
            if (fx.pos === 0 && typeof fx.end == 'string') {
                var start = $.css(fx.elem,'backgroundPosition');
                start = toArray(start);
                fx.start = [start[0],start[2]];
                var end = toArray(fx.end);
                fx.end = [end[0],end[2]];
                fx.unit = [end[1],end[3]];
            }
            var nowPosX = [];
            nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
            nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
            fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

            function toArray(strg){
                strg = strg.replace(/left|top/g,'0px');
                strg = strg.replace(/right|bottom/g,'100%');
                strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
                var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
                return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
            }
        }
    });
})(jQuery);

$('.test').animate({
  'background-position-x': '100px',
  'background-position-y': '200px',
   backgroundPosition:"+100px 200px"
}, 400, 'linear');
Cody Bonney
  • 1,648
  • 1
  • 10
  • 17