Finding element's position relative to the document
You can get top and left without traversing DOM like this:
function getCoords(elem) { // crossbrowser version
var box = elem.getBoundingClientRect();
var body = document.body;
var docEl = document.documentElement;
var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;
var clientTop = docEl.clientTop || body.clientTop || 0;
var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { top: Math.round(top), left: Math.round(left) };
}
You can use element.getBoundingClientRect()
to retrieve element position relative to the viewport.
Then use document.documentElement.scrollTop
to calculate the viewport offset.
The sum of the two will give the element position relative to the document:
element.getBoundingClientRect().top + document.documentElement.scrollTop
You can traverse the offsetParent
up to the top level of the DOM.
function getOffsetLeft( elem )
{
var offsetLeft = 0;
do {
if ( !isNaN( elem.offsetLeft ) )
{
offsetLeft += elem.offsetLeft;
}
} while( elem = elem.offsetParent );
return offsetLeft;
}