Say that I have an element inside a div (or any other containing element, or perhaps just in the body of the document). How do I get the (x,y) coordinates of that element, r
The offsetTop
and offsetLeft
properties are relative to offsetParent
so you can get an element's position relative to its parent for free. If you want the position relative to the entire body
then you need to traverse the offsetParent
chain and sum the values.
The following function accomplishes this:
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}