Animating Elements in jQuery

Elements, like divs, have two properties that determine their positioning on a web page: the top and left properties. The positions can be expressed in either percentage or using a unit of length like pixels or centimeters.

The following code sample illustrates the basic concept underlying an animation, programmatically adjusting the position of an element. In it, any click on the document moves the green div ten pixels to the right.

<!DOCTYPE html>

<html>

<head>

<style type=”text/css”>

div {

position: absolute;

left:10px;

top:10px;

width:20px;

height:20px;

background-color:green;

}

</style>

<script src=”http://code.jquery.com/jquery-1.7.1.min.js”></script>

<script type=”text/javascript”>

$(function(){

$(document).click(function(){

var pos = $(“div”).css(“left”);

pos = parselnt(pos);

$(“div”).css(“left”, pos+10);

});

});

</script>

</head>

<body>

<div>

</div>

</body>

</html>

Instead of having to get the left and top position using $.attr() and converting the result to a number, it’s better to use the $.offset() method, which returns an object containing numeric left and top values indicating the current position of an element relative to the document. The $.offset() method takes the following form:

$(selector).offset();

The following code gets the offset of a div with an id of “box”, and displays the left and top properties with an alert box:

<!DOCTYPE html>

<html>

<head>

<style type=”text/css”>

div {

position: absolute;

left:10px;

top:50px;

width:20px;

height:20px;

background-color:green;

}

</style>

<script src=”http://code.jquery.com/jquery-1.7.1.min.js”></script>

<script type=”text/javascript”>

$(function(){

$(“div#box”).click(function(){

var pos = $(this).offset();

$(“#watcher”).text(pos.top+”:”+pos.left);

});

});

</script>

</head>

<body>

<p>Where is the box? <span id=”watcher”></span></p><div id=”box”></div>

</body>

</html>

Code snippet is from offset.txt

The preceding example displays the coordinates of the div when clicked. You can also use the same offset method to reposition an element:

$(selector).offset(coordinatesObject);

where coordinatesObject is any object that contains a top and left property set to integer values. For example:

$(“div#box”).offset({

top:100,

left:100

});

In the situation were you don’t want to position an element relative to the document, but rather to its parent container you can use the $.position() method instead. The syntax for getting and setting coordinates is identical to $.offset().

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *