Skip to content

Instantly share code, notes, and snippets.

@sevos
Created February 6, 2024 20:56
Show Gist options
  • Save sevos/6b4544f9f0b66b87efc0c27cfc36190b to your computer and use it in GitHub Desktop.
Save sevos/6b4544f9f0b66b87efc0c27cfc36190b to your computer and use it in GitHub Desktop.
<div id="categories" data-controller="persist-scroll-position" data-action="scroll->persist-scroll-position#persist:passive" class="flex-auto flex flex-col gap-4 overflow-y-auto">
...
</div>
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
connect() {
this.element.scrollTop = this.position || 0
}
persist() {
this.position = this.element.scrollTop
}
get storeId() {
return `persisted-scroll-position-${this.element.id}`
}
set position(currentPosition) {
localStorage.setItem(this.storeId, currentPosition);
}
get position() {
return localStorage.getItem(this.storeId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment