jQuery Web Page Design Tutorials

jQuery Animation and Effect Tutorial (Part 3)

We learned how to hide, show and animate opacity of elements in previous jQuery tutorial. Let's learn more interesting jQuery animation and effect in this tutorial.

jQuery Animate Element in Horizontal Direction

This is very easy to animate an element in horizontal direction (i.e. left and right) with jQuery codes. Thefollowing is an example of a basic syntax of animating an element in horizontal direction:

jQuery animate opacity

Animate Element in Left Direction and Right Direction

By controlling the left position, the selected element can be moved to the right side or left side easily.

  • By increasing the value to the left (+=), the element will animate to the RIGHT.
  • By decreasing the value to the left (-=), the element will animate to the LEFT.

This can be shown in the diagram below:

jQuery animate left or right

Example 1:

The following jQuery codes animate the cloud element to the right side by 50 pixels when the Move Cloud to Right button is clicked.

$("#moveCloudRight").click(function() {
$("#cloud").animate( {"left": "+=50px"}, 4000, "linear" );
});

Example 2:

The following jQuery codes animate the cloud element to the left side by 50 pixels when the Move Cloud to Right button is clicked.

$("#moveCloudRight").click(function() {
$("#cloud").animate( {"left": "-=50px"}, 4000, "linear" );
});

Tips:

  • The Duration is an optional parameter. In other words, the following jQuery codes also works:
    $("#cloud").animate( {"opacity": "0"});

  • The Duration parameter can also use "slow", "fast", "normal" or given in milliseconds, i.e.
    $("#cloud").animate( {"opacity": "0"}, "slow");

  • The jQuery animate() Method can also take a callback parameter. The callback parameter is the function to be called or executed after the hide function is completed.

    $(Selected Element).animate({"opacity": "0"}, Duration, callback);

jQuery Callback Example

The jQuery Callback parameter is very useful when you need to do something after the animation is complete. The following is an example of callback. An alert box with the message "Animation completed! The cloud is fully transparent now!" will be pop up after the animation is completed.

$("#opacityCloudShow").click(function() {
$("#cloud").animate( {"opacity": "0"}, 5000, function() { showComplete() } );
});

function showComplete(){
alert("Animation completed! The cloud is fully transparent now!");
}

The callback parameter can also be written as below. Actually most web designers are using this way:

$("#opacityCloudShow").click(function() {
$("#cloud").animate( {"opacity": "0"}, 5000,
function() { alert("Animation Completed"); }
);
});