2

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)

Community
  • 1
  • 1
gasmoor
  • 31
  • 1
  • 4
  • Well the body is constantly at position top 0 because in your css you are telling it to be 100% height of the window and the body is not scrolling, you are scrolling the document/window, and the top element is not scrollable and it is showing 0 because it is not moving on scroll :) – Bojan Petkovski Oct 14 '14 at 09:34
  • to know the position of an element in relation to the top viewport you can use this code: `$('.top').position().top - $('body').scrollTop();` - http://jsfiddle.net/c4tqy3x4/1/ – Frogmouth Oct 14 '14 at 09:36
  • @BojanPetkovski body is actually scroling according to that. scrolltop does update its position. – gasmoor Oct 14 '14 at 10:41
  • 1
    The body is not scrolling, it is at position top 0, check with inspect element to see where is the position of the body and check it's height :) You are seeing the scrollTop of the body only in chrome, check with other browsers :) – Bojan Petkovski Oct 14 '14 at 10:44
  • @BojanPetkovski you are right. Unfortunately I cannot lose the 100% height, it seems that $(window).scrollTop() or $(document).scrollTop() return the same in this case. so I am ok. Thanks. I am slowly getting the hang of Js/Jquery. – gasmoor Oct 14 '14 at 11:24

1 Answers1

3

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.

Jivings
  • 22,834
  • 6
  • 60
  • 101