Getting the current scroll position in Chrome using scrollTop() on page load/refresh

Chris picture Chris · Jul 31, 2013 · Viewed 21.5k times · Source

Running the following in Chrome always returns 0:

$(window).on('load', function(){
     console.log($(window).scrollTop());
});

Running that same command via the console:

$(window).scrollTop()

Does return the correct number. (i.e.: 843)

There are a lot of questions about this issue here on StackOverflow but none of them have given me a correct working answer or alternative. I'm at a loss...

Answer

David Hellsing picture David Hellsing · Jul 31, 2013

The scrollTop() returns the current vertical position of the scroll bar. Typically on page load, the scroll bar is at position 0. If the console prints out something else, then you or the browser must have scrolled down before the function was called.

If you are using named anchors or refreshing the page from a scrolled position, you can bind a handler to the scroll event that only triggers once - on page load:

$(window).on('scroll', function() {
    console.log( $(this).scrollTop() );
});