Keep scroll depth with Turbo frames
Today I learned a nifty Turbo Frames trick: how to persist scroll depth accross a page refresh.
I’m currently working on bundles for cults3D. On the general index of bundles, I have a section displaying 6 bundles manually selected by the Cults’ team. Then, I have my list of bundles sorted by newest to latest.
I’m working on adding a component with some filters in it: toggles, sorting, you know, the work. And this poses a problem: when I toggle a filter, the whole page reloads and I’m back at the top of the page. So to see my filtered bundles, I have to re-scroll through the selected-bundles section, filters, etc… It’s frustating.
Since we’re using Hotwire as a progressive enhancement tech, I used that.
I wrapped my filters component and bundles list in turbo frame tags with three nifty attributes:
autoscroll: truedata-autoscroll-block="start"turbo_action: :advance
autoscroll: true
After the frame’s content is swapped, Turbo scrolls the frame into view. This only happens on frame navigations, not on a first visit or reload.
data-autoscroll-block="start"
This attribute makes the start of the frame to align with the top of the screen.
turbo_action: :advance
This attribute turns a frame navigation to a “full” page visit.
It updates the URL (in my case, with my filters parameters – ie myurl.com?no_ai=true) and adds a history entry on each frame navigation.
Check the documentation here.
The results are really cool!