szTheory / turbolinks-scroll

Persist scroll position between Turbolinks AJAX calls

Home Page:https://www.npmjs.com/package/turbolinks-scroll

Repository from Github https://github.comszTheory/turbolinks-scrollRepository from Github https://github.comszTheory/turbolinks-scroll

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

About

Persist scroll position between Turbolinks AJAX calls

https://www.npmjs.com/package/turbolinks-scroll

License:MIT License


Languages

Language:JavaScript 53.0%Language:TypeScript 47.0%