Reputation: 23583
What is the difference between getBoundingClientRect().top and offsetTop?
https://codepen.io/anon/pen/bWZWQg
const elem = document.querySelector('#find');
console.log('getBoundingClientRect: ' + elem.getBoundingClientRect().top);
console.log('offsetTop: ' + elem.offsetTop);
// Stuff to push the div down the page
<div id='find'>Find me</div>
From my quick test the only difference seems to be the number of decimal places returned.
Upvotes: 35
Views: 47490
Reputation: 889
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.
Upvotes: 32
Reputation: 1243
The method getBoundingClientRect
may not be as good in performance as offsetLeft (doc here), but if you wanna know an element's position after it transformed by CSS, or even still in transition animation, it is the best choice (maybe the only way).
Here is a Related answer.
Upvotes: 4
Reputation: 1432
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.
Upvotes: 18