Sticky
position: sticky that eases in and out. The browser still pins the element.
This adds a small offset on top.
Scroll
Two cards with the same position: sticky. The right one also runs
sticky(). Scroll and compare how each one stops and leaves.
Both cards are plain sticky on this device. The offset runs on pointer devices only, and is off under reduced motion.
A short container. Both eases are shortened to fit.
Sticky does the pinning
The element stays position: sticky and the browser pins it. Nothing is
set to fixed, and no script moves the element while you scroll. The library adds one
offset, on translate.
Where the offset does not run, the element is plain sticky: on touch, under reduced
motion, at a breakpoint that turns sticky off, before the script loads, and after
destroy(). The layout is the same either way.
How it works
Sticky moves an element in three steps: not at all, then with the scroll, then not at all. It changes speed instantly at both ends, which is what looks abrupt. The offset is the difference between that motion and the same motion with both ends eased. It runs as a scroll-driven animation on the compositor, so no script runs while the page scrolls.
Install
npm i @alpacka/sticky
Usage
Keep your existing position: sticky and top. The element's parent must be the box it sticks within.
import { sticky } from '@alpacka/sticky'
const stick = sticky(document.querySelector('.rail'))
stick.freeze() // hold the pose, e.g. before a page transition
stick.destroy() // back to plain sticky
For a virtual scroll, where there is no sticky, curve gives the same maths.
Use clamp where you would clamp the offset.
import { curve } from '@alpacka/sticky'
const c = curve({ travel: 1200, span: innerHeight * 0.4, ease: 'power2' })
const offset = c.clamp(scroll - engage)
Every sticky at once
sticky.all() with no selector finds every sticky on the page. It reads your
stylesheets for rules that set position: sticky, so a sticky that only
applies from a breakpoint up is found at any width and turns on when the rule applies.
import { sticky } from '@alpacka/sticky'
const sticks = sticky.all() // every sticky on the page
const rails = sticky.all('.rail') // or the ones you name
sticks.scan() // look again, after content arrived or left
sticks.freeze()
sticks.destroy()
It is safe to run on every sticky. Ones it cannot ease stay plain sticky: a table header, a site header whose container is the whole page, a sticky inside its own scroll container. Use an attribute to skip an element or give it its own ease.
<aside data-sticky-ease="off">…</aside> <!-- leave this one alone -->
<aside data-sticky-ease="expo" data-sticky-distance="0.3">…</aside>