Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: How to return to the exact same scroll position when going back to previous page

I have a long list of items and when I clicked into each item and return to the main list, the scroll position was lost.

How can I return to the same exact scroll position using jQuery? Is there any easy way to do it?

$(document).ready(function() {

  $('.update-button').click(function (){
    sessionStorage.scrollPos = $(window).scrollTop();
    console.log(sessionStorage.scrollPos);
  });
});

var init = function () {
    //get scroll position in session storage
    $(window).scrollTop(sessionStorage.scrollPos || 0)
};
window.onload = init;

Above is what my code looks like. I tried to log the position and sessionStorage.scrollPos was 0. I am pretty sure I scrolled the page to somewhere.

Help is greatly appreciated.

like image 258
LOCKLOCK Avatar asked Oct 28 '25 01:10

LOCKLOCK


1 Answers

You need to store value of scroll position in sessionStorage (or any storage) and re use it again on page load.

$(window).scroll(function () {
    //set scroll position in session storage
    sessionStorage.scrollPos = $(window).scrollTop();
});
var init = function () {
    //get scroll position in session storage
    $(window).scrollTop(sessionStorage.scrollPos || 0)
};
window.onload = init;
like image 167
Rayon Avatar answered Oct 30 '25 14:10

Rayon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!