gasmoor
gasmoor

Reputation: 31

scrollTop returns 0 except for body

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()

(see Even simplest .scrollTop() example returns 0)

Upvotes: 2

Views: 162

Answers (1)

Jivings
Jivings

Reputation: 23250

Also note on the scrollTop doc page:

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.

In your example the .top element is not scrollable, it's a block that retains it's position regardless of the scrollbar.

However, body is a scrollable element, which is why scrollTop returns a value that represents the distance scrolled through it.

Upvotes: 3

Related Questions