Preserving Scroll Position w/ Turbolinks 09/18/2018

Turbolinks current documentation makes it somewhat unclear whether or not it's responsible for preserving scroll location, but it seems when using .visit, it won't:

Application visits are initiated by clicking a Turbolinks-enabled link, or programmatically by calling Turbolinks.visit(location).
If the visit’s location includes an anchor, Turbolinks will attempt to scroll to the anchored element. Otherwise, it will scroll to the top of the page.

In my case, I wanted to preserve scroll position for links that were going to the same page (I essentially had actions that were changing state and reloading the page). If you're struggling to preserve scroll location, here's some code to get you going:

// Obviously doesn't need to be on window
window.scrollPosition = {x: 0, y: 0} // Our 'old' scroll position
window.lastHref = null // Our 'old' page href

// Before visit, simply store scroll position & url/href
document.addEventListener('turbolinks:before-visit', function () {
  window.scrollPosition = {x: window.scrollX, y: window.scrollY}
  window.lastHref = window.location.href
}, false)

// After load
document.addEventListener('turbolinks:load', function () {
  // If we have a scroll position AND we're on the same page
  if (window.scrollPosition && (this.location.href == window.lastHref)) {
    // Scroll to our previous position
    window.scrollTo(window.scrollPosition.x, window.scrollPosition.y)
  }
}, false)

Implementing this, however, will cause page thrash in most situations, which can be prevented by adding <meta name="turbolinks-cache-control" content="no-preview"> in the header.

Good luck, hope this helps!



Go back