Aug 12, 2007

Animation in jQuery

jQuery provide an function "animate", it can be extended to add your custom animation.

animate(params, speed, easing, callback)

  • params (Hash): A set of style attributes that you wish to animate, and to what end.
  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • easing (String): (optional) The name of the easing effect that you want to use, out of box there are two values "linear" and "swing" (Plugin Required).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

    easing: {

        linear: function( p, n, firstNum, diff ) {

            return firstNum + diff * p;

        },

        swing: function( p, n, firstNum, diff ) {

            return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;

        }

    },

All the build in animate is based on this function

 

The key aspect of this function is the object of style properties that will be animated, and to what end. Each key within the object represents a style property that will also be animated (for example: "height", "top", or "opacity").

Note that properties should be specified using camel case eg. marginLeft instead of margin-left.

The value associated with the key represents to what end the property will be animated. If a number is provided as the value, then the style property will be transitioned from its current state to that new number. Otherwise if the string "hide", "show", or "toggle" is provided, a default animation will be constructed for that property.

 

.