Tuesday, January 1, 2013

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

To calculate the current Position/coordinates of any element relative to the document we can make use of the ".offset()" method of jQuery. ".offset()" method returns an object which consists of Top and Left coordinates.

It is not possible to use this method to calculate the coordinates of elements which uses the CSS property display:none, but possible to calculate the coordinates of elements which uses the CSS property visibility:hidden.

Note: We should use ".position()" method of jQuery to calculate the current Position / coordinates of any element relative to the offset parent.

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

Calculate coordinates using ".offset()" method:

$(document).ready(function(){    
$("*", document.body).click(function (e) {
var coords = $(this).offset();
e.stopPropagation();
$(this).append(" The coordinates of this "+ this.tagName + " tag are: (" + coords.left + ", " + coords.top + " )");
});
});

Example:

<!DOCTYPE html>
<html>
<head>
<style>
  body {background:#F1F1A8;}
  div,article,aside,span,p {padding:0px;margin:0px;cursor:pointer;} 
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){    
$("*", document.body).click(function (e) {
var coords = $(this).offset();
e.stopPropagation();
$(this).append(" The coordinates of this "+ this.tagName + " tag are: (" + coords.left + ", " + coords.top + " )");
});
});
</script>
</head>
<body>
<b>Click on any of the below element to find its coordinates:</b><br/>
<div>This is a div tag.</div>
<article>This is a article tag.</article>
<aside>This is a aside tag.</aside>
<span>This is a span tag.</span>
<p>This is a p tag.</p>
</body>
</html>

Sample output:


How to calculate the current coordinates of any element relative to the document using jQuery

Demo:



0 comments:

Post a Comment

Subscribe via Email