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.
We can use the getBoundingClientRect method to get an element's position relative to its viewport. We get the div with querySelector . Then we call getBoundingClientRect on it to get an object with the top and left properties. top has the position relative to the top of the viewport.
getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport.
If position: absolute; or position: fixed; - the top property sets the top edge of an element to a unit above/below the top edge of its nearest positioned ancestor. If position: relative; - the top property makes the element's top edge to move above/below its normal position.
getBoundingClientRect() gives a result relative to the viewport's top-left corner ( 0,0 ), not relative to an element's parent, whereas el.
You can calculate it using
$('#element').offset().top - $(window).scrollTop() Working example
function get(){    $('#output').html($('#element').offset().top - $(window).scrollTop());  }    get();  $(window).scroll(get);#element {    width:100px;    height:100px;    background:red;  }    #output {    position:fixed;    background:#000;    color:#fff;    width:100%;  }<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div id="output"></div>  <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />  <div id="element"></div>  <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />For those looking for a non-jquery solution:
let el = /* get your el */  let top = el.getBoundingClientRect().top +            el.ownerDocument.defaultView.pageYOffset If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With