Reputation: 61
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
Upvotes: 6
Views: 2523
Reputation: 11607
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:
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.
Upvotes: 1