Sometimes, we want to determine distance from the top of a div to top of window with JavaScript.
In this article, we’ll look at how to determine distance from the top of a div to top of window with JavaScript.
How to determine distance from the top of a div to top of window with JavaScript?
To determine distance from the top of a div to top of window with JavaScript, we can use the top
property.
For instance, we write
const el = document.getElementById("someElement");
const distanceFromTop = el.getBoundingClientRect().top;
to select the element with getElementById
.
Then we call getBoundingClientRect
to get an object with the distance from the top of the window to the top of the element with the top
property.
Conclusion
To determine distance from the top of a div to top of window with JavaScript, we can use the top
property.