Persist scroll position between Turbolinks AJAX calls. Based on code from "How To: Turbolinks 5 Scroll Position Persistence" by Sedad Kosovac
import { turbolinksScrollSetup } from "turbolinks-scroll"
// automatically persist scroll on click or submit
// for any DOM element with data-turbolinks-scroll=false
turbolinksScrollSetup(document)
Set data-turbolinks-scroll=false
DOM elements you want to persist scroll position for on their click
or submit
event
<%= form_with model: @user, url: users_path, data: { 'turbolinks-scroll': false } do |f| %>
<% end %>
<%= link_to 'Users', users_path, 'data-turbolinks-scroll': false %>
import { turbolinksPersistScrollForNextVisit } from "turbolinks-scroll"
// mark the next turbolinks visit to restore scroll position on load
turbolinksPersistScrollForNextVisit()
$.ajax({
type: 'PUT',
url: updateUrl,
data: {
id: id,
position: newPosition
},
success: function (resp) {
},
error: function () {
}
})
import { turbolinksScrollSetTop } from "turbolinks-scroll"
// mark the next turbolinks visit for scroll persistence when `myEvent` is triggered
delegate("[data-turbolinks-scroll]", "myEvent", function (e) {
turbolinksPersistScrollForNextVisit()
}, false)
Note the delegate call above uses the delegate NPM module, which turbolinks-scroll depends on. You could do the same with jQuery like so:
$(document).on("[data-turbolinks-scroll]", "myEvent", function (e) {
turbolinksPersistScrollForNextVisit()
})