JavaScript getBoundingClientRect() changes while scrolling

enzian picture enzian · Sep 2, 2014 · Viewed 87.4k times · Source

I want to have the exact distance between the Y-coordinate of an element an the Y-value=0, which I consider as the top of the document.

myElement.getBoundingClientRect().top;

But the value of getBoundingClientRect() seems to change while scrolling. How can I get the real distance between myElement and the Y-coordinate=0 (top of document)?

Answer

n4m31ess_c0d3r picture n4m31ess_c0d3r · Nov 25, 2014

It is because getBoundingClientRect() gets values with respect to the window(only the current visible portion of the page), not the document(whole page).
Hence, it also takes scrolling into account when calculating its values
Basically, document = window + scroll

So, to get the distance between myElement and the Y-coordinate=0 (top of document), you would have add the value of vertical-scroll also:

myElement.getBoundingClientRect().top + window.scrollY;

Source: https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect