jQuery Animate Effect

Tuesday, July 10, 2012

The jQuery animate method can be used to create a custom animation of your HTML elements simply with the use of CSS properties. This animate method modifies an element's style property in a gradual manner to create the animation effect. The .animate() method allows us to create animation effects on any numeric CSS property. The only required parameter is a map of CSS properties similar to the one that can be sent to the .css() method. Use "+=" or "-=" for relative animations.


Syntax

$(selector).animate({styles},speed,easing,callback)


ParameterDescription
stylesSpecifies one or more CSS properties and values to animate
speedOptional, specifies the speed of the animation
easingOptional, specifies an easing function (swing/linear)
callbackAn optional function to run after the method is completed


Styles

The styles listed in the following table use the DOM naming convention, not CSS. For example note that "paddingLeft" is not "padding-left".


Style
backgroundPosition
borderBottomWidth
borderLeftWidth
borderRightWidth
borderSpacing
borderTopWidth
borderWidth
bottom
font
fontSize
height
left
letterSpacing
lineHeight
margin
marginBottom
marginLeft
marginRight
marginTop
maxHeight
maxWidth
minHeight
minWidth
outlineWidth
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
right
textIndent
top
width
wordSpacing


HTML Example

We will use the following HTML for the examples listed below.


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  // ... jQuery Code ...
});
</script>
</head>
<body>
<img id="img1" src="go.png" /> ; 
<div id="div1"> <!-- Some Content --> </div>
</body>
</html>


Example

Click the image button to animate the div with a number of different properties.


<script type="text/javascript">
 $("#go").click(function () {
        $("#div1").animate({
            width: "82%",
            height: "90px",
            margin: "10px",
            fontSize: "3em",
            borderWidth: "5px"
        }, 2000);
    });
</script">


go arrow
Click the icon!


<script type="text/javascript">
 $("#go").click(function () {
        $("#div1")
          .animate({width: "82%"}, "slow")
          .animate({height: "90px"}, "slow");
    });
</script">


go arrow
Click the icon!


Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

Professional jQuery JavaScript and jQuery: The Missing Manual HTML CSS and JavaScript Editor