jQuery easing function — variables' comprehension

qwertymk picture qwertymk · May 6, 2011 · Viewed 15.2k times · Source

How does the easing function for jQuery work? Take for example:

easeInQuad = function (x, t, b, c, d) {
    return c*(t/=d)*t + b;
};

How does that work? What does each parameter hold? How would I implement some dumb easing for an animation?

Also how would I attach an easing pattern to jQuery, is loading it into $.easing good enough?

Answer

DamonJW picture DamonJW · Jul 26, 2011

According to the jQuery 1.6.2 source, the meaning of the easing function is as follows. The function is called at various points in time during the animation. At the instants it is called,

  • x and t both say what the time is now, relative to the start of the animation. x is expressed as a floating point number in the range [0,1], where 0 is the start and 1 is the end. t is expressed in milliseconds since the start of the animation.
  • d is the duration of the animation, as specified in the animate call, in milliseconds.
  • b=0 and c=1.
The easing function should return a floating point number in the range [0,1], call it `r`. jQuery then computes `x=start+r*(end-start)`, where `start` and `end` are the start and end values of the property as specified in the call to animate, and it sets the property value to `x`.

As far as I can see, jQuery doesn't give you direct control over when the animation step function is called, it only lets you say "if I am called at time t, then I should be thus far through the entire animation." Therefore you cannot, for example, ask for your object to be redrawn more frequently at times when it is moving faster. Also, I don't know why other people say b is the start value and c is the change -- that's not what jQuery source code says.

If you wanted to define your own easing function to do the same as easeInQuad, for example,

$.extend(jQuery.easing,{myfunc:function(x,t,b,c,d) { return x*x; }})

$('#marker').animate({left:'800px'},'slow','myfunc');

$.extend(jQuery.easing,{myfunc:function(x,t,b,c,d) { return x*x; }})

$('#marker').animate({left:'500px'},'slow','myfunc');
#marker { position: absolute; left: 10px; top: 50px; background: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id='marker'>Hello World!</div>