Get an element position relative to the top of the viewport

Viewed 48846

I need to get the top position of an element relative to the top of the viewport, not the whole document.

I tried offset().top; which returns the top position relative to the document, and I tried scrollTop() which always returns 0 regardless of the element's visibility in the viewport.

2 Answers

For those looking for a non-jquery solution:

let el = /* get your el */

let top = el.getBoundingClientRect().top + 
          el.ownerDocument.defaultView.pageYOffset
Related