Here are some improvements on @Pacerier 's code in my own answer:
function getPos(el, rel)
{
var x=0, y=0;
do {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
}
while (el != rel)
return {x:x, y:y};
}
If is just used as getPos(myElem)
will return global position. If a second element is included as an argument (i.e. getPos(myElem, someAncestor)
) that is an ancestor/parent of the first (at least somewhere up the chain) then it will give the position relative to that ancestor. If rel
is not given (i.e. is left undefined
), then it purposefully uses !=
instead of !==
because it should stop when el
gets to null
and rel
is undefined
as well, so the non-strict equality is purposeful, don't change it. It also returns an object, since that's a bit more readable in usage than an array (and so you can do something like getPos().x
).
This is derived from Pacerier's solution, so if you're gonna upvote this, consider upvoting his too.