How to get an element position relative to the top of the viewport with JavaScript?

Sometimes, we want to get an element position relative to the top of the viewport with JavaScript.

In this article, we’ll look at how to get an element position relative to the top of the viewport with JavaScript.

How to get an element position relative to the top of the viewport with JavaScript?

To get an element position relative to the top of the viewport with JavaScript, we can add the top CSS value to the pageYOffset value.

For instance, we write:

<p>
  hello
</p>

to add a p element.

Then we write:

const el = document.querySelector('p')
const t = el.getBoundingClientRect().top +
  el.ownerDocument.defaultView.pageYOffset
console.log(t)

to select the p element with querySelector.

Then we get the p element’s position relative to the top of the viewport by writing:

const t = el.getBoundingClientRect().top +
  el.ownerDocument.defaultView.pageYOffset

Conclusion

To get an element position relative to the top of the viewport with JavaScript, we can add the top CSS value to the pageYOffset value.