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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With