/turbolinks-scroll

Persist scroll position between Turbolinks AJAX calls

Primary LanguageJavaScriptMIT LicenseMIT

turbolinks-scroll

npm version npm size npm size Build Status MIT license npm GitHub stars

Persist scroll position between Turbolinks AJAX calls. Based on code from "How To: Turbolinks 5 Scroll Position Persistence" by Sedad Kosovac

Setup

import { turbolinksScrollSetup } from "turbolinks-scroll"

// automatically persist scroll on click or submit
// for any DOM element with data-turbolinks-scroll=false
turbolinksScrollSetup(document)

Usage

DOM elements

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  %>

AJAX calls

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

Delegating to other events

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