0

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?

Andrei Tornea
  • 108
  • 10

3 Answers3

0

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));
    }
});
MaZoli
  • 1,388
  • 1
  • 11
  • 17
  • It dosen't work as I want, the problem is on refresh to keep the scrolled position, but when I change page to a different one to not keep it – Andrei Tornea Dec 13 '22 at 11:27
  • Do you mean another URL or another page on your URL? – MaZoli Dec 13 '22 at 11:34
  • another url, I was thinking that in the if I can some how use the previous url to compare with the courent one. I saw that there is document.referrer but if you refresh the page it keeps the previouse one and not the refreshed page. – Andrei Tornea Dec 13 '22 at 11:52
0

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.

Andrei Tornea
  • 108
  • 10
-1

you are looking for localStorage which persists until explicitly deleted