How to keep Scroll in last position after page refresh

Asked

Viewed 1,326 times

1

I made some attempts, but I was unsuccessful... The priority is that it be in pure Javascript... But since I could not, I tried with jQuery also.

The situation would be, each time the user increases or decreases the amount of input, the page updates and the Scroll should maintain its last position. In my case he’s going to the top.

Some of my attempts were:

//1)  
var posicaoScroll = $(document).scrollTop();
$(document).scrollTop(posicaoScroll);

//2) "cart-table__product" é a classe a minha lista de produtos no carrinho
$(document).ready(function() {
  $('.cart-table__product').attr({scrollTop: $('.cart-table__product').attr('scrollHeight')});
});

//3)
function scroll() {
  var objScrDiv = document.getElementsByClassName("cart-table__product");
  objScrDiv.scrollTop = objScrDiv.scrollHeight;
}

1 answer

0


I created a script using pure Javascript that saves the last scroll position of the window on localstorage, it always checks on page loading if there is any saved position, if yes, it changes the Scroll position based on it.

var posicao = localStorage.getItem('posicaoScroll');

/* Se existir uma opção salva seta o scroll nela */
if(posicao) {
    /* Timeout necessário para funcionar no Chrome */
    setTimeout(function() {
        window.scrollTo(0, posicao);
    }, 1);
}

/* Verifica mudanças no Scroll e salva no localStorage a posição */
window.onscroll = function (e) {
    posicao = window.scrollY;
    localStorage.setItem('posicaoScroll', JSON.stringify(posicao));
}

Running on the Jsfiddle

  • Thanks @Dobrychtop worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.