Description
This simple script demonstrates the capabilities of the animate method. The animate method essentially manipulates the styles of the targeted element. In this example we have a div with an id of box. We use the animate method on this element to manipulate the box's position and width, first defined in the css.
More info about the animate method (as noted in the jQuery documentation): The key aspect of this function is the object of style properties that will be animated, and to what end. Each key within the object represents a style property that will also be animated (for example: "height", "top", or "opacity"). Note that properties should be specified using camel case, e.g. "marginLeft" instead of "margin-left." The value associated with the key represents to what end the property will be animated. If a number is provided as the value, then the style property will be transitioned from its current state to that new number. Otherwise if the string "hide", "show", or "toggle" is provided, a default animation will be constructed for that property. Only properties that take numeric values are supported (e.g. backgroundColor is not supported).
**Note** As of version 1.3, if you set the duration to 0, the animation will synchronously set the elements to their end state (but it happens instantly).
Demo:
Click on the box below to animate it.
Code:
The following code snippet contains the HTML, CSS, and Javascript necessary for the above demo to work properly. Remember though, that you must also have downloaded and linked to the jquery framework. If you haven't already, you can download that here.
The HTML
<div id="box"></div>
The CSS
<style type="text/css">
#box {background: red; height: 300px; position: relative;}
</style>
The Javascript
<script src="js/jquery.min.js"></script> <!-- This links to the jquery framework. Remember that it must be in your project folder in a folder named 'js' -->
<script type="text/javascript">
$(function() {
$('#box').css("width","250px"); // sets the width of the div with id box to 250px
$('#box').click(function() { // run this function when the div with id box is clicked
$(this).animate({"left" : "300px" }, 1000); // the animate method will take 'this' (div #box) and move it to the left over the course of 4 seconds or 4000 milliseconds. (Note, that is order to move the position of the div, it must have a designated position in the css, thus the position: relative in the css above.)
$(this).animate({ "width" : "50px" }, 4000); // after it moves to the left 300px, we will then change the width of #box to 50px (again over the course of 4 seconds).
// $(this).animate({ "marginLeft" : "650px" }, 4000); // this moves the the box to the left 650 pixels over 4 seconds (be sure to use camelCase when specifying properties - marginLeft vs. margin-left)
});
});
</script>
