skip to Main Content

I’ve a problem when I try to switch between pages.

    $(window).scroll(function () {
        sessionStorage.scrollTop = $(this).scrollTop();
       
    });
    $(document).ready(function () {
        if (sessionStorage.scrollTop != "undefined") {
            $(window).scrollTop(sessionStorage.scrollTop);
        }
    });

I use this script to keep the scrolled position on reload but the problem is that
when I go to another page, it takes the scroled position on the previuos one.
Is there a solution instead of storing the position not in the session but to use the url too?

3

Answers


  1. Chosen as BEST ANSWER

    I've come to a solution.

    thanks to this question How do I detect a page refresh using jquery? and the answer of Uzair

    I've wrote this script

        $(function () {
            if (sessionStorage.tempScrollTop) {
                $(window).scrollTop(sessionStorage.tempScrollTop);
            }
        });
    
        $(window).on("scroll", function () {
            sessionStorage.setItem("tempScrollTop", $(window).scrollTop());
        });
    
        $(window).on('beforeunload', function () {
            sessionStorage.removeItem("tempScrollTop", $(window).scrollTop());
        });
    

    On same page the scrolled position is kept but once i change page it goes to the top.


  2. you are looking for localStorage which persists until explicitly deleted

    Login or Signup to reply.
  3. It’s not beautiful, but it will work:

    $(window).scroll(function () {
       sessionStorage.setItem('scroll-for-'+window.location,(this).scrollTop());
    });
    $(document).ready(function () {
        if (sessionStorage.getItem('scroll-for-'+window.location) != "undefined") {
            $(window).scrollTop(sessionStorage.getItem('scroll-for-'+window.location));
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search