Scrolltop position()

Asked

Viewed 89 times

0

I have a Javascript function that refreshes my page every 15 minutes and I’m trying to get the last position of the scroll bar before the refresh with the jQuery command.

$(window).scrollTop();

Refresh function:

var $myVar = setInterval(myTimer, 900000);

        function myTimer() {
            console.log(scrollPosition);
            loadHs();              

        }

Whenever my page is reloaded it already returns me the value zero, then I would like to rescue the last value as I scroll and set this value rescued after the refresh so that it returns to the previous position.

  • You’ll need to cache the current value of the scroll to be able to redeem after the page refresh.

  • That line localStorage.setItem("timer", true) is why?

  • @Sam this line is no longer part of my code .

1 answer

1


Save the position in a sessionStorage (temporary cookie that will be deleted when leaving the page) and check if it exists and is different from 0 when the page is reloaded. Then use the method window.scrollTo(x,y) to move the screen to the saved position in the cookie.

In case, you will only change the value of the axis y (vertical), leaving the x in 0:

document.addEventListener("DOMContentLoaded", function(){ // aguarda o carregamento do dom
   var pos = sessionStorage.getItem("posicao"); // atribui o cookie a uma variável
   // se a variável tiver valor, move para a posição salva no cookie
   if(+pos) window.scrollTo(0, pos);
});

var $myVar = setInterval(myTimer, 900000);

function myTimer() {
   var scrollPosition = $(window).scrollTop(); // pega a posição do scroll
   sessionStorage.setItem("posicao", scrollPosition); // salva no cookie
   loadHs();
}

Instead of sessionStorage, can use localStorage, the syntax is the same. The difference is that the second generates a permanent cookie.

  • Thanks for the help, but in my case I still get the zero position

  • Try like this on the scroll line: if(+pos) setTimeout(function(){ window.scrollTo(0, pos); }, 10);

  • keeps returning zero I believe it may be because when I access the page for the first time, the scroll bar starts at position 0 and already saves this value. if this is happening it would have to have a method that was checking the position ?

  • Only saves the position value when calling the myTimer() function. How you are reloading the page?

  • Yes, it is correct now I am able to see the last position when I use console.log(), but the bar does not go back to the previous position.

  • you put the setTimeout like I said?

  • I was forgetting that, I made the adjustments and it’s working correctly thanks so much for the help.

Show 2 more comments

Browser other questions tagged

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