I've seen a dozen of script that can catch the x and y position of an element/object within the page. But i am always having trouble with catching the x and y when the webpage is using margins at the body, or other elements, absolute/relative elements, such like that.
Is there a solution wich provides the exact position, no matter what margins or paddings are used.
:)
Getting the exact position is simply a matter of adding the offsetLefts and offsetTops recursively to the offsetParents:
Btw, this solution would probably run twice faster than the other solution above since we only loop once.
I use following code to move div box to follow cursor in this Web IME site
Its return an array [left,top],
YOU's code is downright bad, and I've some improvements on Pacerier's to give, so I'll post my own answer:
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. Ifrel
is not given (i.e. is leftundefined
), then it purposefully uses!=
instead of!==
because it should stop whenel
gets tonull
andrel
isundefined
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 likegetPos().x
).This is derived from Pacerier's solution, so if you're gonna upvote this, consider upvoting his too.
offsetParent
and other offset functions are old... use thegetBoundingClientRect
function... use this:now you can use it like this
Don't worry... no matter how much margin or position or padding the element has, it always works