JavaScript getBoundingClientRect() changes while scrolling

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

Leave a Comment