Categories
JavaScript Answers

How to determine distance from the top of a div to top of window with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *