dzimi
dzimi

Reputation: 829

Get an element position relative to the top of the viewport

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.

Upvotes: 27

Views: 53900

Answers (2)

nikk wong
nikk wong

Reputation: 8690

For those looking for a non-jquery solution:

let el = /* get your el */

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

Upvotes: 17

Mosh Feu
Mosh Feu

Reputation: 29317

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

Upvotes: 36

Related Questions