einstein einstein - 1 year ago 56
Javascript Question

finding element's position relative to the document

What's the easiest way to determine an elements position relative to the document/body/browser window? Right now I'm using ´.offsetLeft/offsetTop´, but this method only gives you the position relative to the parent element, so you need to determine how many parents to the body element, to know the position relaltive to the body/browser window/document position. This method is also to cumbersome.

Answer Source

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;