Jquery - Animate Background position with easing

eleven11 picture eleven11 · Dec 27, 2012 · Viewed 12.3k times · Source

I am trying to animate a background on mousemove with some easing using jquery animate. But cant figure out how to stop the queuing of the animation and have the animation "follow" the mouse around

HTML:

Animate Background<br />
<div id="animateme"></div>​

JS:

$("#animateme").bind('mousemove', function(e) {

    $(this).animate({
        'background-position-x': e.pageX,
        'background-position-y': e.pageY
    }, 100, 'swing');

});​

I have set up a jsfiddle to hopefully show what i mean http://jsfiddle.net/KunZ4/1/

Hover over the top image and you can see the background animation follows the mouse. But i want to add some easing to this, so it follows the mouse a bit smoother.

Using jquery animation seems to queue, but i want the animation to kind of catch up to the mouse on a bit of a delay when mouse movement is stopped.

I am wanting to achieve this without the use of UI or Plugins.

Hopefully that makes some kind of sense

Answer

eleven11 picture eleven11 · Dec 27, 2012

I found something that worked for me, for anyone else looking for this

http://jsfiddle.net/KunZ4/6/

The easing can be adjusted by changing the duration

$.easing.smoothmove = function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
 }; 


$("#animateme").bind('mousemove', function(e){

 $(this).animate({
   'background-position-x': e.pageX,
   'background-position-y': e.pageY
 }, {queue:false,duration:200,easing:'smoothmove'});

 });    

Thanks for all the help