Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between getBoundingClientRect().top and offsetTop?

Tags:

javascript

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.

like image 953
Evanss Avatar asked May 25 '17 05:05

Evanss


People also ask

What is getBoundingClientRect () Top?

getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport.

What is getBoundingClientRect relative to?

getBoundingClientRect() gives a result relative to the viewport's top-left corner ( 0,0 ), not relative to an element's parent, whereas el.

Can I use getBoundingClientRect in react?

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.

Does getBoundingClientRect include margin?

margin is not included.


1 Answers

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. 
like image 105
MehulJoshi Avatar answered Oct 09 '22 00:10

MehulJoshi