I am trying to fing the offsets of an element using element.getBoundingClientRect(), however the problem with this is if the webpage is long in terms of height and there is scrolling involved the function returns the offsets of the element w.r.t the window. How do I get the offsets w.r.t the top of the page?
-
1Tip: You can get the distance scrolled as another value which will let you get the value you want. – Marty Sep 12 '16 at 06:15
-
I'm sorry, that won't be useful in my case. – Diablo3093 Sep 12 '16 at 06:17
-
1I think you'll find it is exactly what you need... – Marty Sep 12 '16 at 06:20
-
1Marty is right, check out this [answer](http://stackoverflow.com/questions/25630035/javascript-getboundingclientrect-changes-while-scrolling/27129257#27129257) – n4m31ess_c0d3r Sep 12 '16 at 06:22
-
@Marty that solves it. Thanks – Diablo3093 Sep 12 '16 at 07:06
1 Answers
The documentation for getBoundingClientRect()
covers your use case in a brief example:
The amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the bounding rectangle. This means that the rectangle's boundary edges (top, left, bottom, and right) change their values every time the scrolling position changes (because their values are relative to the viewport and not absolute). If you need the bounding rectangle relative to the top-left corner of the document, just add the current scrolling position to the top and left properties (these can be obtained using
window.scrollX
andwindow.scrollY
) to get a bounding rectangle which is independent from the current scrolling position.

- 39,033
- 19
- 93
- 162