Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain Scroll Position of large HTML page when client returns

Tags:

I'm serving very long html pages (short ebooks)

When client returns, too much of a hassle to try to find exact place where left off due to long html page.

Is there a simple way to maintain the scroll position automatically so that next time the client returns to the page the page scrolls down automatically to where he left off. this needs to be transparent, i.e. no clicking to "store" scroll position.

like image 810
Ray S. Avatar asked May 05 '13 20:05

Ray S.


People also ask

How does browser remember scroll position?

More specifically, it's a get/set property on the scroll bar object. When you navigate to another page, the browser stores the number corresponding to the current scroll bar position with the page URL. When you navigate back to that page, the browser recalls the scroll bar position.

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 maintain the scroll position react?

By default you can set the value of scrollPosition is 0 . Here I have used the sessionStorage to maintain the scroll position for demo purpose. You can also use the context API or redux store to manage it.

How do you get the scroll position in HTML?

To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.


2 Answers

The steps are simple, but the solution to this question depends on your app implementation, you can:

  • Retrieve the current scroll position, you can use:

    window.pageYOffset

  • Store the position, this has two parts, when and where:

    • You can chose to store the data, when the window closes, or every time the user scroll, or on a set interval...

    • for the "where", depending on your app, you may want to store it, in a cookie, local-storage, on the server-side (if the user needs to log in to read the eBook)...

  • Restore the position when the user return, by retrieving the stored data, and scroll to that position using

    window.scrollTo(0, position);

so the real problem here is, when and where to store the position, and that depends on your application.

like image 121
TedMeftah Avatar answered Oct 23 '22 12:10

TedMeftah


I made small jquery plugin that you can include and have this functionallity without cookies etc. Include just before end of body tag.

  <script type="text/javascript" src="/js/maintainscroll.jquery.min.js"></script> </body> 

https://github.com/evaldsurtans/maintainscroll.jquery.js

like image 37
Evalds Urtans Avatar answered Oct 23 '22 12:10

Evalds Urtans