Search code examples
javascriptjquerybrowserback-button

How to take user back to where they scrolled to on the previous page when clicking the browser's back button?


Is it possible to take a user back to the area of a page where they scrolled down to when pressing the back button in a browser?

An example to illustrate the goal:

  1. pageA is double your screen size (hence you have to scroll to read more).

  2. You click a link on pageA to go to a new page - pageB.

  3. After reading, you click the browser's back button.

  4. When you return to pageA, you are back at the position you were reading.

In reality, the back button goes back to the top of the previous page, and have to scroll down to where I was to continue reading the rest of the page.

Is there a JQuery or JavaScript way to return to that point in the page? Maybe something with .scrollTop()?


Solution

  • If the content is loaded after the page "load" event firing, then the back button will not take you back to the position you were, because the browser scrolls before the 'load' event.

    To make the browser remember the scroll position in this case, you have to store the scroll position and status (what content have been loaded) somewhere before navigating away. Either in the cookie, or in the url hash.

    If pageA is just a static page without dynamic content (loaded after 'load' event, the browser should remember the scroll position when you go back.

    For dynamic content, there at least includes two parts. One is recovering the page status when click "Back" button, so all the dynamic content is loaded, some expander are expanded or collapsed. The other is scroll to there.

    The first part depends on how the page is implemented. The 2nd part you can put the scroll top into the cookie when page doing onUnload. For example

    $(window).unload(function() {$.cookie('scrollTop',$(window).scrollTop());});