27

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.

0

2 Answers 2

36

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 />

0
16

For those looking for a non-jquery solution:

let el = /* get your el */

let top = el.getBoundingClientRect().top + 
          el.ownerDocument.defaultView.pageYOffset
1
  • 1
    Thanks. I myself came here looking for jQuery equivalent of getBoundingClientRect :) Jun 6, 2021 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.