Sometimes, we want to get the distance from the top for an element with JavaScript.
In this article, we’ll look at how to get the distance from the top for an element with JavaScript.
How to get the distance from the top for an element with JavaScript?
To get the distance from the top for an element with JavaScript, we get the sum of the window.pageYOffset
property and the element’s top
value.
For instance, we write
const elDistanceToTop = window.pageYOffset + el.getBoundingClientRect().top;
to use window.pageYOffset
to get the vertical offset of the page.
Then we get the element’s computed position values with getBoundingClientRect
.
And we use the top
property to get the top position of the el
element.
We add them together to get el
‘s distance from the top of the page.
Conclusion
To get the distance from the top for an element with JavaScript, we get the sum of the window.pageYOffset
property and the element’s top
value.