How to keep the Scroll in the last position after refreshing the page

1

I made a few attempts, but I was not successful ... The priority is to be in pure JavaScript ... But as I could not, I tried with jQuery as well.

The situation would be, each time the user increases or decreases the amount in the input, the page refreshes and the Scroll should keep 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;
}
    
asked by anonymous 07.11.2018 / 13:51

1 answer

0

I created a script using pure JavaScript that saves the last position of the window Scroll in localstorage , it always checks the page loading if there is any saved position, if it does, it changes the Scroll position based on it. p>

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 in JSFiddle

    
07.11.2018 / 14:38