Difference between offsetParent and parentElement or parentNode
Using getBoudingClientRect() is really a great help (thanks Ally for the hint!).
If you still need the position relative to the upper left corner of the document, here's a helpful snippet:
if (node.getBoundingClientRect) {
var rect = node.getBoundingClientRect();
var sx = -(window.scrollX ? window.scrollX : window.pageXOffset);
var sy = -(window.scrollY ? window.scrollY : window.pageYOffset);
return {
x: rect.left - sx,
y: rect.top - sy
}
}
Note: document.body.getBoundingClientRect()
may return an unexpected value for top
in Firefox under some circumstances. Therefore, the window scroll position is more robust.
For the client who do not yet support getBoundingClientRect(), we still must walk the offetParents and take care that every overflow: scroll
(or auto) parent has position: relative
.
offsetParent
is the closest parent that has position:relative
or position:absolute
or the body of the page. parentNode
is the direct parent, regardless of position
.
Stay clear of offsetParent
, you'll have to add lots of hacks and checks to ensure you get it right.
Try using getBoundingClientRect instead.