Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist scrolls with turbolinks?

Tags:

turbolinks

Sometimes it is desirable to persist scroll positions between page visits.

Turbolinks resets scroll position after loading the data.

How can I disable it for particular elements?

like image 842
Vedant Agarwala Avatar asked Sep 24 '16 17:09

Vedant Agarwala


1 Answers

My solution in ES6:

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()

And add on your links data-turbolinks-persist-scroll=true on links you want persist scrollbar position.

<a href="..." data-turbolinks-persist-scroll=true>Link</a>

This works for me, also with link_to remote: true.

like image 83
Pioz Avatar answered Oct 14 '22 09:10

Pioz