how to remember scroll position of page

前端 未结 7 1745
南笙
南笙 2020-12-15 00:31

I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was

相关标签:
7条回答
  • 2020-12-15 01:33

    I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling.


    Here's a jquery way of doing it:

    jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames )

    Very importantly, you'll need the jquery cookie plugin.

    jQuery:

    // When document is ready...
    $(document).ready(function() {
    
        // If cookie is set, scroll to the position saved in the cookie.
        if ( $.cookie("scroll") !== null ) {
            $(document).scrollTop( $.cookie("scroll") );
        }
    
        // When a button is clicked...
        $('#submit').on("click", function() {
    
            // Set a cookie that holds the scroll position.
            $.cookie("scroll", $(document).scrollTop() );
    
        });
    
    });
    


    Here's still the code from the original answer:

    jsfiddle

    jQuery:

    // When document is ready...
    $(document).ready(function() {
    
        // If cookie is set, scroll to the position saved in the cookie.
        if ( $.cookie("scroll") !== null ) {
            $(document).scrollTop( $.cookie("scroll") );
        }
    
        // When scrolling happens....
        $(window).on("scroll", function() {
    
            // Set a cookie that holds the scroll position.
            $.cookie("scroll", $(document).scrollTop() );
    
        });
    
    });
    

    @Cody's answer reminded me of something important.

    I only made it to check and scroll to the position vertically.

    0 讨论(0)
提交回复
热议问题