Anthony L.
Anthony L.

Reputation: 101

reload page after back button but keep scroll position

I am writing a simple PHP Ajax CRUD. After editing data for a row in edit.php, I hit Go back button with window.history.back();

The data is updated on MySQL but the main list (after go back) wasn't updated. I guess I should use reload() but if I use that, whenever the page is reloaded, the scroll position will jump to top, which is not so convenient for users.

I searched some solutions that store scroll position to a local storage then call it back after reloading, but I have no idea where to start with. Any idea for this?

Upvotes: 0

Views: 1097

Answers (2)

Anthony L.
Anthony L.

Reputation: 101

I figured out the solution. The page when use window.history.back(); is not updated. Then we need to reload it whenever it is navigated back by window.history.back(); Otherwise, it will be loaded only once.

Here is the solution: LINK

So by reloading it self, most browser will keep the same scroll y as before. So I'm good to go

Upvotes: 0

Mystical
Mystical

Reputation: 2783

Use GET parameters to save the position of your scroll, while still refreshing:

var scroll = document.documentElement.scrollTop; // get page scroll
location.href = '?scroll=' + scroll; // refresh page and save scroll as a GET parameter

And add this somewhere at the beginning of your script (so you can check to see if a scroll parameter is set and scroll to that position):

// get scroll parameter
var scrollFromGet = location.search.match(/scroll=(\d+)/);

// set scroll if there is any
if(scrollFromGet[1]) 
    document.documentElement.scrollTop = scrollFromGet[1];

Upvotes: 1

Related Questions