2

There were some problems, led to scrolling "contents_container" instead of scrolling "body".

From then on, click "history.back" to forget the scroll position.

I found jquery cookie but it doesn't works.

// 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() );

});

});

and this too.

if (history.scrollRestoration === 'manual') {


 history.scrollRestoration = 'auto';
}

and this too.

I really want to remember the page's scroll position.

Here is my css code and could you fix the problem?

.contents_container {width: 100%; height: 100%; overflow-y: scroll; position: relative; float:left;}

Thank you.

yjdev
  • 77
  • 1
  • 8

1 Answers1

3

I made it on popstate, you can achieve this on 'beforeunload' even on this event page still exist but is not visible. (if is server side rendered)

window.addEventListener('popstate', onLocationChange);

function onLocationChange(e){
    const scrollY = window.scrollY || window.pageYOffset;
    localStorage.setItem("scrollY", scrollY)
}

window.addEventListener("load", onPageLoad);

function onPageLoad(){
   const scrollY = parseInt(localStorage.getItem("scrollY"));
   if(scrollY && !isNaN(scrollY)) {
       window.scrollTo(0, scrollY)
   } 
}

for overflowded container


window.addEventListener('popstate', onLocationChange);

function onLocationChange(e){
    //if(document.location.test() or startsWith() .... 
    // to fire only on desired pages
    const container document.querySelector('.contents_containe');
    const scrollTop = container.scrollTop;
    localStorage.setItem("container-scrollTop", scrollTop)
}

window.addEventListener("load", onPageLoad);

function onPageLoad(){
   const scrollTop = parseInt(localStorage.getItem("container-scrollTop"));
   if(scrollTop && !isNaN(scrollTop)) {
      const container document.querySelector('.contents_containe');
      container.scrollTop = scrollTop;
   } 
}

19h47
  • 46
  • 1
  • 1
  • 6
Robert
  • 2,538
  • 1
  • 9
  • 17
  • Thank you but it doesn't works. I think the problem is ".contents_container"'s "overflow-y:scroll", but I want to know remember the scroll position inside ".contents_container". – yjdev Dec 30 '20 at 03:16
  • So, just remember position of container.scrollTop on page change location and then. set this position on page load. Like in this code but change window.scroll on container.scrollTop. – Robert Dec 30 '20 at 05:44