Skip to content

Instantly share code, notes, and snippets.

@jessehanley
Created April 10, 2019 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessehanley/8b4dca7deb53ef77fd3f5746e9d792aa to your computer and use it in GitHub Desktop.
Save jessehanley/8b4dca7deb53ef77fd3f5746e9d792aa to your computer and use it in GitHub Desktop.
Persistent Scroll for Turbolinks
const turbolinksPersistScroll = () => {
const persistScrollDataAttribute = 'turbolinks-persist-scroll'
let scrollPosition = null
let enabled = false
document.addEventListener('turbolinks:before-visit', (event) => {
if (enabled)
scrollPosition = window.scrollY
else
scrollPosition = null
enabled = false
})
document.addEventListener('turbolinks:load', (event) => {
const elements = document.querySelectorAll(`[data-${persistScrollDataAttribute}="true"]`)
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', () => {
enabled = true
})
}
if (scrollPosition)
window.scrollTo(0, scrollPosition)
})
}
turbolinksPersistScroll();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment