https://github.com/sztheory/turbolinks-scroll
Persist scroll position between Turbolinks AJAX calls
https://github.com/sztheory/turbolinks-scroll
ajax node npm position rails rails-ujs scroll stimulus turbolinks ujs
Last synced: about 1 month ago
JSON representation
Persist scroll position between Turbolinks AJAX calls
- Host: GitHub
- URL: https://github.com/sztheory/turbolinks-scroll
- Owner: szTheory
- License: mit
- Created: 2019-10-13T01:49:20.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-04T22:36:39.000Z (over 2 years ago)
- Last Synced: 2025-04-10T23:36:14.339Z (about 1 month ago)
- Topics: ajax, node, npm, position, rails, rails-ujs, scroll, stimulus, turbolinks, ujs
- Language: JavaScript
- Homepage: https://www.npmjs.com/package/turbolinks-scroll
- Size: 271 KB
- Stars: 4
- Watchers: 2
- Forks: 1
- Open Issues: 12
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# turbolinks-scroll
[](https://badge.fury.io/js/turbolinks-scroll)   [](https://travis-ci.org/szTheory/turbolinks-scroll) [](https://lbesson.mit-license.org/) [](https://www.npmjs.com/package/turbolinks-scroll) Persist scroll position between Turbolinks AJAX calls. Based on code from ["How To: Turbolinks 5 Scroll Position Persistence"](https://medium.com/@kosovacsedad/how-to-turbolinks-5-scroll-position-persistence-6e4435a60b2e) by Sedad Kosovac
## Setup
```Javascript
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
```erb
<%= 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
```JavaScript
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
```JavaScript
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](https://www.npmjs.com/package/delegate) NPM module, which turbolinks-scroll depends on. You could do the same with jQuery like so:
```js
$(document).on("[data-turbolinks-scroll]", "myEvent", function (e) {
turbolinksPersistScrollForNextVisit()
})
```