Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 701
Chris Avatar asked Jul 31 '13 07:07

Chris


2 Answers

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() );
});
like image 111
David Hellsing Avatar answered Sep 22 '22 15:09

David Hellsing


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
    
like image 22
Ronak Patel Avatar answered Sep 22 '22 15:09

Ronak Patel