html/js: go back to previous page in the same scroll position

Let's just say I have a page that is quite long, like an article. There's a link like buy full article now or something. When clicked it will redirect to a page that contains all my script, add the article to the database, and redirect back again to the article page. Is this possible? and also, how can I make it that it will redirect to same scroll position that the user was browsing?

Good example of this is like the BACK button on the browser. It will take you to the previous page you visited, at the same scrolling position

Answers 1

  • From this question:

    During page unload, get the scroll position and store it in local storage. Then during page load, check local storage and set that scroll position. Assuming you have a div element with id element. In case it's for the page, please change the selector :)

    $(function() {
       $(window).unload(function() {
          var scrollPosition = $("div#element").scrollTop();
          localStorage.setItem("scrollPosition", scrollPosition);
       });
       if(localStorage.scrollPosition) {
          $("div#element").scrollTop(localStorage.getItem("scrollPosition"));
       }
    });
    

Related Articles