11

I don't know if anyone is still using Sammy.js, but I found it perfectly suits my needs for a lightweight routing and templating library. If anyone has other ideas, please let me know.

My problem is that when I have a long page and I scroll down, click on a link on this page and go back, the whole page is reloaded (in Sammy, the GET route is called) and it jumps to the top of the page.

My question is: Is there a way to have Sammy cache the page and maintain the scroll position when going back in the history?

Thanks in advance.

Lasse Bunk
  • 1,848
  • 20
  • 21
  • 1
    As a workaround I suggest, http://stackoverflow.com/a/5651372/2346893 combined with http://stackoverflow.com/a/10115269/2346893, You can also add id of the current visible element to the hash history as you scroll through the page, if you don't want to do it manually. – Gokhan Kurt May 11 '16 at 07:03
  • you can use localstorage to pass scrolltop and url as parameters in each visited page. –  May 15 '16 at 00:20

1 Answers1

6

You could use localStorage as alternative way to store url-scrolltop as a pair. This way the browser remembers srolltop position for the specified url.

var scroltop,url;
$(window).scroll(function() {
    scroltop = $(this).scrollTop();
    url = window.location.href;
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
    localStorage.setItem(url,scroltop);
    }, 250));
});
if(localStorage.getItem(window.location.href)) {
  url = window.location.href;
  scroltop = localStorage.getItem(url);
  $(window).scrollTop(scroltop);   
}

JSbin example