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.
getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport.
getBoundingClientRect() gives a result relative to the viewport's top-left corner ( 0,0 ), not relative to an element's parent, whereas el.
You can use Element. getClientRects() and Element. getBoundingClientRect() to get the size and position of an element. In React, you'll first need to get a reference to that element.
margin is not included.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With