Difference between getBoundingClientRect().top and offsetTop?

getBoundingClientRect gives you offset relative to your client viewport, While offsetTop is always fixed static property. although it changes when the actual position of the element changes on document. For real clarification go to pen and you can check the difference your self.

If element is inside relative container then offsetTop will be relative to the given container pen

console.log('offsetTop: ' + elem.offsetTop); //This is fixed. it get's calculated from beginning of your page to actual element's position.

console.log('getBoundingClientRect: ' + elem.getBoundingClientRect().top); // this will changing while scroll, because it's relative to your current view port.

see the pen, scroll the div and while doing that check the console.

In case container of the element is relative then

console.log('offsetTop: ' + elem.offsetTop) // //This is fixed. it get's calculated from beginning of your top most relative container.

The HTMLElement.offsetTop read-only property returns the distance of the current element relative to the top of the offsetParent node.

getBoundingClientRect() is a very useful, cross browser safe method that returns top, right, bottom, and left position of any element relative to the viewport.

Tags:

Javascript