Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery animate background position

I can't seem to get this working.

$('#product_family_options_dd').animate({
  height: '300px',
  width: '900px',
  backgroundPosition: '-20px 0px',          
},

The height and width animate but not the background.

like image 775
jimbo Avatar asked Mar 02 '11 17:03

jimbo


4 Answers

You don't need to use the background animate plugin if you just use separate values like this:

$('.pop').animate({
  'background-position-x': '10%',
  'background-position-y': '20%'
}, 10000, 'linear');
like image 151
nnyby Avatar answered Nov 01 '22 10:11

nnyby


I guess it might be because it is expecting a single value?

taken from the animate page on jQuery:

Animation Properties and Values

All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.) Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.

like image 35
Luke Duddridge Avatar answered Nov 01 '22 11:11

Luke Duddridge


Since jQuery doesn't support this out of the box, the best solution I have come across so far is to define your own CSS hooks in jQuery. Essentially, this means to define custom methods to get and set CSS values which also works with jQuery.animate().

There is already a very handy implementation for this on github: https://github.com/brandonaaron/jquery-cssHooks/blob/master/bgpos.js

With this plugin in place, you can do something like this:

$('#demo1').hover(
  function() {
    $(this).stop().animate({
      backgroundPositionX: '100%',
      backgroundPositionY: '100%'
    });
  },
  function () {
    $(this).stop().animate({
      backgroundPositionX: '105%',
      backgroundPositionY: '105%'
    });
  }
);

For me, this worked on all browsers tested so far including IE6+.

I did put a quick demo online a while ago and you can rip it apart if you need further guidance.

like image 35
bfncs Avatar answered Nov 01 '22 09:11

bfncs


jQuery's animate function is not exclusively usable for directly animating properties of DOM-objects. You can also tween variables and use the step function to get the variables for every step of the tween.

For example, to animate a background-position from background-position(0px 0px) to background-position(100px 500px) you can do this:

$({temporary_x: 0, temporary_y: 0}).animate({temporary_x: 100, temporary_y: 500}, {
    duration: 1000,
    step: function() {
        var position = Math.round(this.temporary_x) + "px " + Math.round(this.temporary_y) + "px";
        $("#your_div").css("background-position",  position);
    }
});

Just make sure to not forget the this. inside the step function.

like image 9
eelkedev Avatar answered Nov 01 '22 09:11

eelkedev