Question

I need to trigger a page reload, via JS, preserving the vertical scroll position.

I'm using the solution described in another SO question:

  1. Calculate the current scroll position
  2. Add the current position as a querystring argument, then redirect
  3. When the page reloads, read the value from the querystring & adjust the scroll pos

However, I only want to restore the scroll position on that FIRST redirect. If the user scrolls around the page and then triggers a manual reload using Ctrl-R, I do NOT want to re-scroll to that saved position.

Is there some way of passing a single-use, visible-to-the-next-request-only value using ONLY JavaScript? Or from removing a value from document.location.href without redirecting?

Should I be using the HTML 5 History API to "clear" the position value after I've consumed it?

Était-ce utile?

La solution

Save the value to sessionStorage. Once you use it, delete the value so it cannot be read on a manual refresh.

sessionStorage.setItem("scroll_position", "300");
sessionStorage.getItem("scroll_position"); // 300
sessionStorage.removeItem("scroll_position");

sessionStorage is really well-supported -- it'll will work fine for IE8+ any relevant version of the other browsers.


StackOverflow handles after-page-load scrolling by storing post id's in the URL hash. You could do that as well.

The url stackoverflow.com/...../21485393#21485393 has #21485393 which matches an anchor element <a name="21485393"></a> It will automatically scroll to that element after the page loads.

You could do something like that as well.

http://your.url.com/page#300

Retrieve it with

window.location.hash

And remove it once you're done by

window.location.hash = ""
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top