Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  45] [ 5]  / answers: 1 / hits: 51382  / 8 Years ago, wed, march 23, 2016, 12:00:00

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.


More From » jquery

 Answers
20

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




[#62834] Monday, March 21, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ulysses

Total Points: 111
Total Questions: 118
Total Answers: 113

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
;