Search code examples
cssparallax

Maintaining scroll position on refresh/back with CSS parallax


When doing a CSS parallax effect, I've used CSS like this:

#wrapper {
  perspective: 1px;
  transform-style: preserve-3d;
  height: 100vh;
  overflow-x: hidden;
  overflow-y: scroll;
}

.parallax-container {
  position: relative;
  transform: translateZ(-1px) scale(2);
  z-index: -1;
}

This works great and I've very happy with the effect. One unintended side-effect of the full-viewport wrapper element though is that the browser's usual behaviour of scrolling back to its previous position on refresh, or back button, no longer works. As far as the browser's concerned, it's not scrolled at all as all the scrolling is done on the wrapper's overflow-y.

Is there anything I can do to fix this or is it a limitation of this technique?


Solution

  • You can try the following solution. It stores the wrapper's scroll position in localStorage and then restores that position when the browser reloads:

    window.addEventListener("unload", function(e) {
        var wrapper = document.getElementById("wrapper");
        var previousScroll = wrapper.scrollTop;
        window.localStorage.setItem("previousScroll",previousScroll)
    }
    document.addEventListener("DOMContentLoaded", function(e) {
       var wrapper = document.getElementById("wrapper");
       var previousScroll = window.localStorage.getItem("previousScroll")
        wrapper.scrollTop = previousScroll;
    });