Understanding jQuery animate() function

jQuery animate() function is very powerful API to manipulate html elements and add animation functionality. The use of animate function is very simple. First lets check the syntax of this function. .animate( properties, [ duration ], [ easing ], [ callback ] )
  • properties: A map of CSS properties that the animation will move toward.
  • duration: A string or number determining how long the animation will run.
  • easing: A string indicating which easing function to use for the transition.
  • callback: A function to call once the animation is complete.
.animate( properties, options )
  • properties: A map of CSS properties that the animation will move toward.
  • options: A map of additional options to pass to the method. Supported keys:
    • duration: A string or number determining how long the animation will run.
    • easing: A string indicating which easing function to use for the transition.
    • complete: A function to call once the animation is complete.
    • step: A function to be called after each step of the animation.
    • queue: A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately.
    • specialEasing: A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions (added 1.4).
Lets learn the animate() function with set of examples. First include the jQuery javascript library in your html file. Add following in your html <HEAD> tag:
<SCRIPT type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></SCRIPT>
Code language: HTML, XML (xml)
For all the demos, we will use a sample DIV tag for animating. Following is the div code and its stylesheet.
<style type="text/css"> #content { background-color:#ffaa00; width:300px; height:30px; padding:3px; } </style> <input type="button" id="animate" value="Animate"/> <div id="content">Animate Height</div>
Code language: HTML, XML (xml)

Animate height/width

Animating height and width in jQuery is very easy. Lets assume you have a DIV that you want to animate i.e. increase the height.
$("#animate").click(function() { $("#content").animate( {"height": "80px"}, "fast"); });
Code language: JavaScript (javascript)
Demo 1: Also following will be the code to animate Width of the element.
$("#animate").click(function() { $("#content").animate( {"width": "350px"}, "fast"); });
Code language: JavaScript (javascript)
Demo 2:

Animate opacity

$("#animate").click(function() { $("#content").animate( {"opacity": "0.15"}, "slow"); });
Code language: JavaScript (javascript)
Demo 3:

Moving elements using animate()

<STYLE> #content { background-color:#6688ff; position:absolute; width:100px; height:100px; padding:3px; margin-top:5px; left: 100px; } </STYLE> <input type="button" id="left" value="Left"/> <input type="button" id="right" value="Right"/> <div id="content">Move</div>
Code language: HTML, XML (xml)
$("#right").click(function() { $("#content").animate( {"left": "+=50px"}, "slow"); }); $("#left").click(function() { $("#content").animate( {"left": "-=50px"}, "slow"); });
Code language: JavaScript (javascript)
Demo 4:

Callback Function

Callback functions are very useful to perform certain activity when the animation is completed. Also note here when multiple elements are mapped with the animation and we have specified a callback function. Then the callback will get called for each of the element. Let us see an example where we use callback function to display a message when animation is completed.
$("#animate").click(function() { $("#content").animate( {"height": "100px", "width": "250px"}, "slow", function(){ $(this).html("Animation Completed"); }); });
Code language: JavaScript (javascript)
Demo 5:

Combine multiple animations

You may want to combine multiple animations. Following are few demos will help you understanding this. Example 1: Animate both height and width at same time. This example is pretty straight forward. You can animate both height and width at same time by specifying it in animate function. For example: In below code we specified height and width value in animate function.
$("#animate").click(function() { $("#content").animate( {"height": "100px", "width": "250px"}, "slow", ); });
Code language: JavaScript (javascript)
Example 2: Queuing the animations.
$("#animate").click(function() { $("#content") .animate({"height": "100px"}, 500) .animate({"width": "250px"}, 500); });
Code language: JavaScript (javascript)
Demo 6:

Queuing of Events

In above demo (Demo 6) we saw that when we queued up the events with multiple .animate() method call, the animation is actually queued up. i.e. it completes the first animation and then proceed with next. Let see an example were we use queue parameter to disable queuing. In following example we have set parameter queue to false. The code is exactly same as demo 6, only change we added is queue = false. Also note that queue parameter is added with second argument.
$("#animate").click(function() { $("#content") .animate({"height": "100px"}, {"queue": false, "duration": 500}) .animate({"width": "250px"}, 500); });
Code language: JavaScript (javascript)
Demo 7:
Get our Articles via Email. Enter your email address.

You may also like...

47 Comments

  1. Vikas says:

    Ah… I guess you will explain how internally animate & fx function deals with timer queue!

  2. rys says:

    nice one, but I have something to ask if jquery work in a fancybox…?.

  3. builder says:

    Great tutorial. Thanks!

  4. Love the tutorial…thanks and great work

  5. Moorthy says:

    Really nice one. great work. thanks buddy. try to keep on update

  6. sachin says:

    tohh…his is great

  7. This is really great. Thanks for the compilation!

  8. dYcA says:

    prikitiuw… great tutorial.
    thx plen

  9. oyun says:

    I lıve jQuery.I love jQuery animation.=)

  10. IP says:

    Awesome tutorial. Thanks lots. God bless you!

  11. mahesh says:

    nice one, but I have something problem in dremweaver or in browser please solve the problem which browser support this jquiry
    i write the code like this in dremweavercs5.5

    Untitled Document

    #content {
        background-color:#ffaa00;
        width:300px;
        height:30px;
        padding:3px;
    }
    
    $("#animate").click(function() {
        $("#content").animate(
                {"height": "80px"},
                "fast");
    });
    

    Animate Height

    but it is not work

  12. mahesh says:

    ok brother great work it is working nice ,thnaking you ,god is bless you soooooooooomuch you, nice days brother

  13. confusecious says:

    Thanks for the examples!!

    For ‘moving elements’, (demo 4):

    If I click on ‘left’…it moves 50px, click again and moves 50px. But I only need to move it once, the second click i want it to be still.

    How would I do that?

    thanks

    • @Confusecious – To achieve such functionality you can define a flag and use it to animate/move element only once. For example:

      var leftflag = false;
      $("#left").click(function() {
         if(!leftflag) {
         leftflag = true; 
             $("#content").animate(
                     {"left": "-=50px"},
                     "slow");
         }
      });
      


      Hope this works :)

      • Neha says:

        Hi Viral,
        Your code mentioned above to click only once will work with Single Link button.If i have multiple link button my navigation is not working on send click.It is working when i am clicking first time.

        Can you please help me on this.

        • Neha says:

          Hi Viral,
          Updated Text…

          Your code mentioned above to click only once will work with Single Link button.If i have multiple link button my animationis not working on second click.It is working when i am clicking first time only(i.e. on first link button in )

          Can you please help me on this.

  14. CS95 says:

    Very usefull tutorial.

  15. Alt says:

    How does the reset button (next to the animate buttons) work?

  16. vijay says:

    i like your tutorial.
    i teach it.
    it’s very nice.

  17. zamaan says:

    great tuto. nice examples. really helped in my project. thanks alot.

  18. Harry says:

    Awesome tutorial.nice example of animate function

  19. Giorgio says:

    Congratulation for the clarity and many thanks!

  20. Pradeep says:

    Nice tutorial..really helpfull

  21. Hello,

    I am found the jQuery animate function related to the information with php in google. & I have obtain new link related to jQuery animate function with php.These link very useful to my project & other work. This link is….

    http://www.phphunt.com/122/animate-example-in-jquery?show=123#a123

  22. Matth Jenks says:

    Thank you. Very helpful for those of us who want to *learn* jquery rather than just *copy* someone else’s code.

  23. lakshmi says:

    how to make movement of moving boxes as much as fast, with out affecting other animations

  24. MickeyNotD says:

    I working with Demo 5, the Callback Function. I don’t want to use the “Reset” button. Instead, I’d like to have a “Back” text link at the end of the text in the expanded window. For example, check the last line of code; I wrote what I need to happen in UPPER CASE :

    <script type="text/javascript">
    $("#animate").click(function() {
    	$("#content").animate(
    			{"height": "100px", "width": "250px"},
    			"slow", function(){
    				$(this).html("<b>bunch of text here.</b> THEN HERE, HAVE A "Back" TEXT LINK THAT HAS THE SAME EFFECT AS RESET");
    			});
    });
    
    </script> 

    If worse came to worse, then a button would be OK too. Using a text link i’s more for aesthetic purposes in the case.

    Thanks.

    Mickey

  25. Neha says:

    Hi Viral,
    Updated Text…

    Your code mentioned above to click only once will work with Single Link button.If i have multiple link button my animationis not working on second click.It is working when i am clicking first time only(i.e. on first link button in )

    Can you please help me on this.

  26. kensley says:

    This post is very nice but its missing one tiny tiny tiny addition that will make it amazing…
    Click the same button a second time and have the box animate in reverse process. How hard is it to do that? What steps are involved?

    Thanks again

  27. praveen says:

    I want more real time examples to understand jquery plz sent some exp

  28. ajai says:

    good examples……

  29. chanchal says:

    Thanks.Its good and helpful

  30. Tarocchi amore says:

    Need some more tutorials like this

  31. suresh kumar s says:

    Itz very basic tutorial right…i want more recent animate concepts….

  32. Saravanan says:

    Nice tutorials… Thanks ……..

  33. Nisha says:

    Give me more in detail

  34. Gurpreet says:

    It is very helpful tutorial for me….

    Thanks guys..!!

  35. Saujanya Reddy says:

    Thank you for your tutorial :)

  36. Ravikumar says:

    Super………

  37. Fhumz says:

    Howzit Bra,
    I am loading content into a div using AJAX. The div has a minimum height of 300px and as such when i load content the div expands to various heights depending on the height of the loaded content. i would like the div’s height to animate each time new content is loaded.

    Please assist me. Thanks in advance

  38. BBera says:

    I have three animation function

    setTimeout(function() {
    $(“.lock10”).animate({opacity: “toggle”}, 5000).delay(3000).animate({opacity: “toggle”}, 5000)
    },5000);

    setTimeout(function() {
    $(“.lock10”).animate({opacity: “toggle”}, 5000).delay(3000).animate({opacity: “toggle”}, 5000)
    },7000);

    setTimeout(function() {
    $(“.lock10”).animate({opacity: “toggle”}, 5000).delay(3000).animate({opacity: “toggle”}, 5000)
    },9000);

    I want to restart all from first AFTER COMPLETE all animation

    don’t want to use SetInterval

  39. Kirtan Patel says:

    Hi,

    My below code not working for ie 7,8,9 version,

    Please help me.

    <html>
    <head>
        <title>html scale demo </title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <style type="text/css">
            html, body {
                padding: 0;
                margin: 0;
            }
    
            #div1 {
                
                background-color: #ff0000;
                width:100%;
                height:200px;
            }
        </style>
        <script type="text/javascript">
            function anim()
            {
                $("#div1").animate({ "opacity": "0.5" }, {
                    step: function (now, fx) {
                        $(this).css('-webkit-transform', 'scale(' + now + ')');
                        $(this).css('-moz-transform', 'scale(' + now + ')');
                        $(this).css('-ms-transform', 'scale(' + now + ')');
                        $(this).css('-o-transform', 'scale(' + now + ')');
                        $(this).css('transform', 'scale(' + now + ')');
                    },
                    duration: 1200
                }, 'linear');
            }
    
            function reset()
            {
                $("#div1").removeAttr("style");
            }
        </script>
    </head>
    <body>
        <div id="div1">
            dummy test gose here
        </div>
        <button id="btnAnimate" onclick="anim();"  type="button" >Animate</button>
        <button id="btnReset" onclick="reset();"  type="button" >Reset</button>
    </body>
    </html>
    

  40. Selvam says:

    It is very helpful tutorial for me….
    Thanks

  41. Chris says:

    Thanks for this!
    @BBera: Maybe this will help you. Its a function to solve a similar problem.

    function blink() {
        var o1 = $('#test span').first();
        var o2 = $('#test span').next();
        o2.hide();
        $('#test span').css('position', 'absolute');
        var animate = function() {
            var c = 0;
            o1.fadeOut(1500, function() {ready(++c);});
            o2.fadeIn(1500,  function() {ready(++c);});
        };
        var ready = function(a) {
            if(a === 2){
                var tmp = o1;
                o1 = o2;
                o2 = tmp;
                animate();
            }
        }
        animate();
    }
    

  42. jitu says:

    i Love This Ecample

  43. suraj says:

    Wow Amazing example thanks for sharing

  44. Harold.Stanford says:

    Every successful person has a beginning

Leave a Reply

Your email address will not be published. Required fields are marked *