I am expecting this is the correct behaviour of scrollTop
, but I keep reading differently in posts, so I am really looking for an explanation of why this happens.
From Jquery's documentation:
*
"The vertical scroll position is the same as the number of pixels that are hidden from view above the scrollable area. If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0."
*
So I would expect scrollTop
to change as the element goes out of the viewport, however this does not happen. See JSFiddle.
http://jsfiddle.net/c4tqy3x4/
The relevant code:
$(window).scroll(function(){
bodyPos= $('body').scrollTop();
topPos = $('.top').scrollTop();
$('.body').text('the body element\'s position is: '+bodyPos);
$('.top').text('the top element\'s position is: '+topPos);
})
For the record, from another post, this would return the position of elements in relation to the top of viewport:
$("span").offset().top - $(document).scrollTop()