Wednesday, January 2, 2013

How to set the current coordinates to any element relative to the document using jQuery?

To set the current Position/coordinates to any element relative to the document we can make use of the ".offset(coordinates)" method of jQuery. "coordinates" is an object which has the properties top and left, these are integer values indicating the new top and left coordinates for the selected elements. 

The ".offset(coordinates)" method is used to re-position any selected element. The element's position properties top and left are specified relative to the document.

Note: If we are using this method on an element which already has the position style property set as static, then that elements position will be set to relative to allow for this re-positioning.

1. How to calculate the current coordinates of any element relative to the document using jQuery?
2. How to set the current coordinates to any element relative to the document using jQuery?(this article)

Set coordinates using ".offset(coordinates)" method:

$(document).ready(function(){     
$("p:last").offset({ top: 28, left: 60 }); 
});

Example:

<!DOCTYPE html>
<html>
<head>
<style>
  body {background:#F1F1A8;}
  p {padding:8px;margin:0px;} 
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){    
$("p:last").offset({ top: 28, left: 60 });
});
</script>
</head>
<body>
<p>This is first paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
<p>This is fourth paragraph.</p>
<p>This is fifth paragraph.</p>
</body>
</html>

Sample output:


How to set the current coordinates to any element relative to the document using jQuery

Demo:



0 comments:

Post a Comment

Subscribe via Email