Home > Enterprise >  Keep scrolled position of page on reload or change page discarding previous
Keep scrolled position of page on reload or change page discarding previous

Time:12-13

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?

CodePudding user response:

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));
    }
});

CodePudding user response:

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.

CodePudding user response:

you are looking for localStorage which persists until explicitly deleted

  • Related