jQuery Web Page Design Tutorials

jQuery Animation and Effect Tutorial (Part 4)

This jQuery tutorial shows how to animate selected element in vertical direction.

jQuery Animate Element in Vertical Direction

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

jQuery animate vertical

Animate Element Up and Down

By controlling the top position, the selected element can be moved up and down easily.

  • By increasing the value to the top (+=), the element will animate DOWN.
  • By decreasing the value to the top (-=), the element will animate UP.

This can be shown in the diagram below:

jQuery animate up down

Example 1:

The following jQuery codes animate the sun element UP by 30 pixels when the Move Sun Up button is clicked.

$("#moveSunUp").click(function() {
$("#sun").animate( {"top": "-=30px"}, 4000, "linear" );
});

Example 2:

The following jQuery codes animate the sun element DOWN by 30 pixels when the Move Sun Down button is clicked.

$("#moveSunDown").click(function() {
$("#sun").animate( {"top": "+=30px"}, 4000, "linear" );
});

Tips:

  • The Duration is an optional parameter. In other words, the following jQuery codes also works:
    $("#sun").animate( {"top": "+=30px"});

  • The Duration parameter can also use "slow", "fast", "normal" or given in milliseconds, i.e.
    $("#sun").animate( {"top": "+=30px"}, "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({"top": "+=30px"}, 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!" will be pop up after the animation is completed.

$("#moveSunDown").click(function() {
$("#sun").animate( {"top": "+=50px"}, 5000, function() { showComplete() } );
});

function showComplete(){
alert("Animation completed!");
}

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

$("#moveSunDown").click(function() {
$("#sun").animate( {"top": "+=50px"}, 5000,
function() { alert("Animation Completed"); }
);
});