8

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

Chris
  • 3,680
  • 6
  • 26
  • 43

2 Answers2

11

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() );
});
Kyle Baker
  • 3,424
  • 2
  • 23
  • 33
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • 2
    That is why the question says page load/refresh. Because with a refresh the browser retains its scroll position and that is exactly what I'm looking after. – Chris Jul 31 '13 at 08:02
  • I clarified the answer to point out that the solution also covers the auto-scroll feature some browsers have on refresh. – David Hellsing Jul 31 '13 at 08:06
  • @David I found this Q&A very useful but I've realized that if I bind the handler to the `scroll` event it always returns 0 (because the browser hasn't scrolled, so you need to scroll first to see the value change). While if I bind it to the `load` event, it returns the scrolled position where I am (Chrome v30, Firefox v24). – ithil Oct 07 '13 at 10:19
  • very good and clever solution for getting browser's back button cached scroll value, thanks. – Barlas Apaydin Apr 21 '14 at 10:14
1

There are many ways to get the current scroll position In page

  1. First get pageYOffSet let verticalScrollOffset = window.pageYOffset;

    then Set window.scrollTo(0,verticalScrollOffset);

  2. If you need both Side position and set then

    let scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
    let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    
    window.scrollTo(scrollLeft,scrollTop);
    
  3. Using ViewportScroller click here to know more this.viewportScroller.scrollToPosition(this.viewportScroller.getScrollPosition());//does not helps in my case

  4. Ideal Solution works for me, I just save verticalScrollOffset(YaxisSrollPosition) before loading the page or refresh in any constant variable or local storage.Then After Refresh or load the page Use that position

    let verticalScrollOffset = window.pageYOffset || document.documentElement.scrollTop;
    
    $("html, body").animate({ scrollTop: verticalScrollOffset }, "slow");//slow Or fast option