Sometimes, we want to find element’s position relative to the document with JavaScript.
In this article, we’ll look at how to find element’s position relative to the document with JavaScript.
How to find element’s position relative to the document with JavaScript?
To find element’s position relative to the document with JavaScript, we can get the sum of the top
value of the element and the document’s scrollTop
value.
For instance, we write
element.getBoundingClientRect().top + document.documentElement.scrollTop;
to get position of the element relative to the top of the viewport with element.getBoundingClientRect().top
.
And we add the viewport offset with scrollTop
and add that to top
.
Conclusion
To find element’s position relative to the document with JavaScript, we can get the sum of the top
value of the element and the document’s scrollTop
value.