Because elements in HTML can be positioned using CSS, we can animate them, by changing the position, size, opacity, etc.
Just like jQuery allows us to show or hide an element, fade them in and out, or even slide elements, it can allow them to animate with a method. There are two main parameters which you will use, one is required, one is optional.
Required Parameter
The required parameter is a JavaScript Object which will specify what changes to the CSS that is needed. This however, isn’t like what you probably found using the .css() parameter.
You can specify a property you want to set, and a value. The parameter needs to be numeric in value. jQueryUI expands upon this, allowing you to also change color values. Setting a value is normal. However, your parameter can be an exact value, or it can be relative. Look at the examples below:
// this set the left side of the element to be 50 pixels // from the left of its parent element. $('#obj').animate({ 'left':'50px' }); // move the element 50 units to the left of its current position $('#obj').animate({ 'left': '+=50' });
As a note, make sure you don’t have any spaces inside your quotes. It will cause jQuery to ignore the property.
The += means to add to the current value, and set it. This would be used to move to the right or down from it’s current location. It could also be used to make the object more opaque. -= would be used to subtract from that value, this would be used to move an element, up, to the left, or make it more transparent – just to name a few.
One thing you can’t do however is animate the visibility. You would need to use chaining to animate that.
Optional Parameters
There are several optional parameters that you may use.
duration
The duration is the optional parameter that you are most likely to use. It sets how long your animation will take, in milliseconds to complete. By default, it is set for 400 milliseconds, however, as with fadeIn()
/fadeOut()
, you can use fast
, slow
, or a numeric representation.
easing
Easing is normally only used if you are going to animate over a longer distance or time. You can use swing
by default, or linear
. The jQueryUI library has more easing options.
complete (function)
This allows you to have a function run once the animation completes. This could be used to chain animations, set values, and do more. What ever you need.
Sometimes it is helpful, sometimes it isn’t necessary. That’s the nice thing about it be optional. It isn’t required to be used.
Using jQuery to Animate HTML Elements was originally found on Access 2 Learn