I'm trying to get the coordinates of an element on a page. I've been using the standard way to obtain it:
var el = element, pos = {x: 0, y: 0};
while ( el ) {
pos.x += el.offsetLeft;
pos.y += el.offsetTop;
el = el.offsetParent;
}
But this method fails when the element in question has display: block
, and one of the offsetParents has display: inline;
. This is due to the fact described in this thread:
After some trying with jQuery it turns out that their .offset()
-method returns the correct offset, and I've looked through the source but not found exactly how they do it. So my question is: how do I get the exact position? I can't use jQuery for this project, and the method in the thread described earlier is to cumbersome, adding an element and testing is too much work (performance perspective), and using Element.getBoundingClientRect
is not available either.
If you feel like trying it out you can go to Apple.com open your debugger of choice and type in the following:
var el, el2;
el = el2 = document.querySelector('#worldwide span');
var pos = {x: 0, y: 0};
while ( el2 ) {
pos.x += el2.offsetLeft;
pos.y += el2.offsetTop;
el2 = el2.offsetParent;
}
alert("Calculated position: " + pos.x + "x" + pos.y + " window size: " + screen.width + "x" + screen.height);
With this code I get: Calculated position: 1354x988 window size: 1280x800
(ie. the offset left is way of the screen, which it clearly isn't)
How is this possible? Any work-around ideas? Approximations? It does not have to be exact, but it has to be better than before. Thanks.
Edit: This is for the WebKit rendering engine, to clarify.