jQuery: basic animations

jQuery's animations are actually performed by the animate() method. Let's start with a simple HTML structure:

<div id="container">

<div class="left"></div>
<div class="right"></div>

</div>

with the following styles:

#container {

    width: 400px;
    height: 100px;

}

.left {

    background: orange;
    width: 100px;
    height: 100px;
    float: left;
    position: relative;

}

.right {

    background: yellow;
    width: 100px;
    height: 100px;
    float: right;
    position: relative;

}

We want the two floated elements exchange their position within their container. The jQuery code is really simple:

$(document).ready(function() {

    $('#animate').click(function() {
    
        $('.left').animate({left: '300px'}, 'slow');
        $('.right').animate({right: '300px'}, 'slow');
        
        return false;
    
    });

});

The offset for the animation is given by the subtraction of the overall width of the container minus the width of each box. The second parameter determines the speed of the animation (in this case is slow). Optionally the animate() method accept a callback function to be executed as the third parameter when the animation is complete. You can see the final result here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.