Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintaining Scroll Position With Back Button and Ajax Dom Manipulation

I am loading results in with ajax with an infinite scroll, however, when you click an item in the list and navigate away from the page, then click the back button, you are back at the top of the list.

I can't figure out how to make the user return to the position they left off.

See the site I am working on: https://www.studenthouses.com/search/manchester/

Scroll down a few times, then click a property, then click back and you will see what I mean.

I can't remember the result position and load them in because it would take too long, so really I need the browser to remember the DOM when it comes back to the page, or cache it some how.

Is there a solution to this?

Many thanks

like image 302
user3229006 Avatar asked Jan 31 '14 15:01

user3229006


People also ask

How can I retain the scroll position of a scrollable area when pressing back button?

store the position in cookies and after that use the cookie to scroll the page to exact position .

How do you keep the scroll position?

Preserve scroll position allows you to maintain the same scroll location when you transition between two screens. This applies to scroll depth in a vertical scroll, as well as the user's location inside a horizontal scrolling element. Figma automatically preserves your scroll position for Smart Animate.

What is Ajax scroll?

Infinite Ajax Scroll is a javascript infinite scrolling plugin. It works by reading the next (and previous) links of your existing server-side pagination and load these pages via AJAX when the visitor scrolls to the end of the page.


1 Answers

Sure there is and it's a piece of cake. Well, it's a cookie, actually :)

You don't need much to solve this problem.

First, get some cookie here: Cookie API

Second, you'll have to encode the data in the cookie somehow. If you have multiple pages like that one, you'll have to separate them somehow or use a key-value pair and store something like this:

manchester=3522

Whenever you enter the page, load the cookie, wait the page to be fully unrolled (you use AJAX or similar, you'll have to wait for the page being unrolled, window.onload won't do).

If there is no cookie, skip this step:

  • scroll the page down to the offset you have loaded from the cookie: scrollTo

Next, whenever the page is scrolled, modify the cookie. To avoid thrashing you'll want to do this in a polling manner. Use setInterval() at maybe 500 milliseconds and check if the user changed the scrolling position. If he did, save the cookie with the new value.

like image 131
pid Avatar answered Oct 25 '22 15:10

pid