You can animate an element on a page with jQuery by changing its CSS properties, setting them in a special jQuery function, called animate.

animate method

The animate() allows us to create animation effects on any numeric CSS property.
The animate() function can be used with this sintax:
animate(
{
 property1: value,
 property2: value,
 property3: value
}, duration, easing, complete)
- The set of CSS properties (within curly braces) is the only required parameter. You can add as many CSS properties as you need, but their name must be the name used in JavaScript (for example, marginLeft, instead of margin-left and backgroundColor instead of background-color).
- duration - (optional) sets the speed of the animation. It can be the strings "fast" and "slow", or a number that indicates the speed in milliseconds.
- easing - (optional) specifies the speed at which the animation progresses. There are two types of easing available to use in jQuery: "linear" and "swing" (default).
- complete - (optional) represents a function that is fired once the animation is complete.

jQuery will set the new CSS styles, but instead of setting them instantly (as CSS would do), it does so gradually, animating the effect at the chosen speed.
The animated properties can be fixed (e.g.: marginRight: '100px'), or relative, using += or -= to add or subtract the given number from the current value of the property (e.g.: marginRight: '+=80px').

Example. When a button is clicked, animates some properties of a <div>. When animation is finished, changes the text in the button:
<style type="text/css"><!--
#dv1 { width:50px; height:50px; background:#bebefe; font-size:11px; }
--></style>

<script type="text/javascript"><!--
$(document).ready(function() {
  // when the tag with id="btn" is clicked, animate some properties of the element with id="dv1"
  // then change the text in the #btn
  $('#btn').click(function() {
    $('#dv1').animate(
    {
      width: '150px',
      height: '80px',
      marginLeft: '+=80px',
      fontSize: '22px'
    }, 2000, 'linear', function() {
      $('#btn').text('Click again');
    });
  });
});
--></script>

<div id="dv1">Some content</div>
<button id="btn">Click</button>
Demo:
Some content

In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle' (e.g.: width: 'toggle').
Example: Animates the element with id="dv" to toggle width, height, opacity and fontSize, completing the animation within 2500 milliseconds. When animation is finished, changes the text in the button.
<style type="text/css"><!--
#dv1 { display:none; width:150px; height:80px; background:#bebefe; }
--></style>

<script type="text/javascript"><!--
$(document).ready(function() {
  // when the tag with id="btn" is clicked, animate to toggle some properties of the element with id="dv1"
  // then change the text in the #btn
  $('#btn').click(function() {
    $('#dv1').animate({
      width: 'toggle',
      height: 'toggle',
      opacity: 'toggle',
      fontSize: 'toggle'
    }, 2500, function() {
      $('#btn').text('Click again');
    });
  });
});
--></script>

<div id="dv1">Some content</div>
<button id="btn">Click</button>
Demo:

In addition to style properties, some non-style properties such as scrollTop and scrollLeft can be animated.
Example. Animate scroll down the page 400 pixels, by setting the vertical scroll bar to +400 (scrollTop: '+=400'):
<script type="text/javascript"><!--
$(document).ready(function() {
  // when tag with id="btn" is clicked, sets the vertical scroll bar to +400
  $('#btn').click(function() {
    $('html, body').animate({
      scrollTop: '+=400'
    }, 1400, 'linear');
  });
});
--></script>

<button id="btn">Scroll Down</button>
Demo

animate() advanced options

The animate() method has an advanced version with additional options.
Syntax:
animate(
{
  property1: value,
  property2: value,
  property3: value
},
{
  duration: value,
  easing: value,
  complete: function() { code to execute when animation is finished },
  step: function(now, fx) { code to execute, using now and fx parameters },
  queue: boolean_value
})
- The set of CSS properties (within curly braces) is the only required parameter. You can add as many CSS properties as you need.
- duration - (optional) sets the speed of the animation; "fast", "slow", or a number that indicates the speed in milliseconds.
- easing - specifies the speed at which the animation progresses: "linear", or "swing" (default).
- complete - (optional) defines a function that will be executed when animation finished.
- step - (optional) a callback function that is fired at each step of the animation. This function is useful for enabling custom animation types or altering the animation as it is occurring. It accepts two arguments (now and fx):
        - now - the numeric value of the property being animated at each step.
        - fx - a reference to the jQuery.fx object, which contains a number of properties such as elem for the animated element, start and end for the first and last value of the animated property, respectively, and prop for the property being animated.
              For example, to get the ID of the current animated element:     var id_elm = fx.elm.id;
- queue - (optional) a Boolean value (true, or false) indicating whether to place the animation in the effects queue.

The queue is the list of animations waiting to occur on a particular element. Every time we ask jQuery to perform an animation on an element, that animation is added to the queue. The element executes the queue one at a time until everything is complete. If you disable the queue (set false) when you specify an animation, the animation will begin immediately.


Example. Animate the height and width of two <div> elements. When the integer value of the width of the first DIV reaces 160, starts to animate the second element.
<style type="text/css"><!--
#dv1 { width:200px; height:80px; background:#a7a8fe; }
#dv2 { width:100px; height:40px; background:#07fe08; }
--></style>

<script type="text/javascript"><!--
$(document).ready(function() {
  // when tag with id="btn" is clicked, animates the width and height of two elements
  $('#btn').click(function() {
    // starts animate #dv1
    $('#dv1').animate(
    {
      width: '100px', height: '40px'
    },
    {
      duration: 2000,
      easing: 'linear',
      step: function(now, fx) {
        // gets the current width (integer) of the #dv1 during the animation
        var wh = Math.floor(now);

        // if the width of the #dv1 reaces 160, starts to animate #dv2
        if(wh==160) {
          $('#dv2').animate(
          {
            width: '200px', height: '80px'
          }, 2000);
        }
      }
    }
    );
  });
});
--></script>

<button id="btn">Click</button>
<div id="dv1">Div 1</div>
<div id="dv2">Div 2</div>
Demo:
Div 1
Div 2

Color animation

The animate() method creates animation effects on numeric CSS property, most properties that are non-numeric (color, backgroundColor) cannot be animated using basic jQuery functionality.
To animate colors, you need a special jQuery plugin which can be downloaded from Color animation jQuery-plugin.
Or, you can copy the code below and save it in a ".js" file on your server.

jQuery Color Animations plugin

'use strict';(function(d){function h(a,b,e){var c="rgb"+(d.support.rgba?"a":"")+"("+parseInt(a[0]+e*(b[0]-a[0]),10)+","+parseInt(a[1]+e*(b[1]-a[1]),10)+","+parseInt(a[2]+e*(b[2]-a[2]),10);d.support.rgba&&(c+=","+(a&&b?parseFloat(a[3]+e*(b[3]-a[3])):1));return c+")"}function f(a){var b;return(b=/#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(a))?[parseInt(b[1],16),parseInt(b[2],16),parseInt(b[3],16),1]:(b=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(a))?[17*parseInt(b[1],16),17*parseInt(b[2], 16),17*parseInt(b[3],16),1]:(b=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(a))?[parseInt(b[1]),parseInt(b[2]),parseInt(b[3]),1]:(b=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9\.]*)\s*\)/.exec(a))?[parseInt(b[1],10),parseInt(b[2],10),parseInt(b[3],10),parseFloat(b[4])]:l[a]}d.extend(!0,d,{support:{rgba:function(){var a=d("script:first"),b=a.css("color"),e=!1;if(/^rgba/.test(b))e=!0;else try{e=b!=a.css("color","rgba(0, 0, 0, 0.5)").css("color"), a.css("color",b)}catch(c){}return e}()}});var k="color backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor outlineColor".split(" ");d.each(k,function(a,b){d.Tween.propHooks[b]={get:function(a){return d(a.elem).css(b)},set:function(a){var c=a.elem.style,g=f(d(a.elem).css(b)),m=f(a.end);a.run=function(a){c[b]=h(g,m,a)}}}});d.Tween.propHooks.borderColor={set:function(a){var b=a.elem.style,e=[],c=k.slice(2,6);d.each(c,function(b,c){e[c]=f(d(a.elem).css(c))});var g=f(a.end); a.run=function(a){d.each(c,function(d,c){b[c]=h(e[c],g,a)})}}};var l={aqua:[0,255,255,1],azure:[240,255,255,1],beige:[245,245,220,1],black:[0,0,0,1],blue:[0,0,255,1],brown:[165,42,42,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgrey:[169,169,169,1],darkgreen:[0,100,0,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkviolet:[148,0,211,1],fuchsia:[255, 0,255,1],gold:[255,215,0,1],green:[0,128,0,1],indigo:[75,0,130,1],khaki:[240,230,140,1],lightblue:[173,216,230,1],lightcyan:[224,255,255,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],magenta:[255,0,255,1],maroon:[128,0,0,1],navy:[0,0,128,1],olive:[128,128,0,1],orange:[255,165,0,1],pink:[255,192,203,1],purple:[128,0,128,1],violet:[128,0,128,1],red:[255,0,0,1],silver:[192,192,192,1],white:[255,255,255,1],yellow:[255,255, 0,1],transparent:[255,255,255,0]}})(jQuery);

After you have saved the Color Animations plugin on your server, include it in your HTML document (in the <head>...</head> section). You must have both files with jQuery library and color plugin included in the HTML document, like in this sintax:
<head>
 <title>Page Title</title>
 <script type="text/javascript" src="jquery_library.js"></script>
 <script type="text/javascript" src="jq_color_plugin.js"></script>
</head>
You can now animate color properties in your jQuery animation code, just as you would other CSS properties.

Example. When the user clicks on an HTML element (a <div>), animate its width, height, backgroundColor, and color.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Color animation</title>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript" src="jq_color_animate.js"></script>
<style type="text/css"><!--
#dv1 { width:150px; height:60px; background:#a7a8fe; cursor:pointer; }
#dv1 em { display:none; }
--></style>

<script type="text/javascript"><!--
$(document).ready(function() {
  // when click on element with id="dv1", animate its width, height, backgroundColor, and color
  $('#dv1').click(function() {
    $(this).animate(
    {
      'width':'300px', 'height':'100px',
      'backgroundColor':'#7efe8f', 'color':'#0101fe'
    }, 2000, function() {
      $(this).find('em').fadeIn(900);
    });
  });
});
--></script>
</head>
<body>
Click:
<div id="dv1">jQuery Tutorials, and other Web Development Courses:<br />
<em>coursesweb.net/javascript/</em></div>
</body>
</html>
Demo, click on the rectangle below:
Click:
jQuery Tutorials, and other Web Development Courses:
coursesweb.net/javascript/

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used in <table> to create table header cell?
<thead> <th> <td>
<table><tr>
  <th>Title 1</th>
  <th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin
.some_class {
  line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()
document.getElementById("id_button").onclick = function(){
  window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()
$ar_dir = scandir("dir_name");
var_export($ar_dir);
Animating CSS properties with jQuery

Last accessed pages

  1. innerHTML and outerHTML to Get and Replace HTML content (15094)
  2. PHP MySQL - WHERE and LIKE (16145)
  3. Zodiac Signs JavaScript code (3802)
  4. Writing PHP scripts (8702)
  5. Zodiac Signs PHP code (2838)

Popular pages this month

  1. Qwop (2996)
  2. Get Attribute (ID, Class, Name, Title, Src) with jQuery (2372)
  3. Get the value of the selected /checked checkboxes in a form (1497)
  4. Insert, Select and Update NULL value in MySQL (1339)
  5. Add, Change, and Remove Attributes with jQuery (1225)