logo javascript

Javascript Course for Beginners

Instructor: Ivan Lourenço Gomes

jQuery - Animate

Besides the methods seen in the previous lesson, jQuery offers another way of adding effects to HTML elements through the animate() method. This method allows us to control different CSS properties.

                    

    $("element").animate({property: value}, speed, callback function);

                    
                

The first argument is an object composed of CSS properties and values. One cool thing is that we can use the incremental operator for the values.

                        
    
        $("#animate").click(function(){
            $("#square").animate({
                width: '+=20px',
                height: '+=20px'
            });
        }); 
    
                        
                    

In the above example, the two properties were changed at the same time. If we would like to change the height only after the width change is finished, we don't need to use the callback function because animate methods used in sequence automatically wait for the previous one to finish before they start, working as a queue.

                    

    $("#animate").click(function(){

        $("#square").animate({
            width: '+=20px'
        },500);

        $("#square").animate({
            height: '+=20px'
        }),500;

    });

                    
                
Important:
  • Most CSS properties can be animated, except colors.
  • The CSS properties that don't follow the variable naming rules have to be written in the lower camel case style, like paddingLeft or borderRadius.
  • Contents