Web Development
GSAP Observer: Wheel, Touch and Pointer in One API
Observer is the GSAP plugin that folds a mouse wheel, a finger on a touch screen and a dragging mouse, which each fire their own events (wheel, touch* and pointer*), into one config. It reports which way the gesture went and how fast, without moving anything on its own. It has been free since 3.13.
The docs use it for full-screen sections that change with the wheel. In the middle of an article that would hijack the scroll, so the demo in this post is a panel of four slides in a box that change with the wheel or a sideways swipe, while a vertical swipe keeps scrolling the page.
This post is part of the GSAP series. Licensing and installation live in the series hub, and matchMedia and gsap.context in post 2, on the core. ScrollTrigger, from post 5, reacts to scrolling that already happened; Observer reacts to the gesture. Making the element itself follow the finger is a job for Draggable, from post 8. The demo runs on GSAP 3.15.0, and two script tags are enough:
<script src="https://unpkg.com/gsap@3.15.0/dist/gsap.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/Observer.min.js"></script>
<script>
gsap.registerPlugin(Observer);
</script>
The basics: Observer.create()
Here is the example from the Observer docs, pointed at an element instead of the window:
// Assumes a .panel and two functions, previous() and next().
Observer.create({
target: ".panel", // defaults to the viewport
type: "wheel,touch",
onUp: () => previous(),
onDown: () => next()
});
"Down" means the delta grows, as when a finger drags downward. type accepts "wheel", "touch", "pointer" (any non-touch mouse or pointer) and "scroll"; the default is "wheel,touch,pointer". As it stands, a trackpad burst (five wheel events in 100 ms) calls next() five times.
What each callback gets
Every callback receives the Observer instance, with deltaX and deltaY (pixels since the last callback on that axis), velocityX and velocityY (pixels per second), x, y, the original event, isDragging and isPressed:
// Assumes a .readout element on the page.
Observer.create({
type: "wheel,touch,pointer",
onChange: (self) => {
document.querySelector(".readout").textContent =
Math.round(self.deltaY) + " px, " + Math.round(self.velocityY) + " px/s";
}
});
There are also onLeft, onRight, onDragStart, onDrag, onDragEnd, onPress, onRelease, onWheel, onStop and onHover. Moving the mouse without pressing doesn't count; defining onMove makes Observer measure that too.
Tuning the gesture
| Option | What it does |
|---|---|
tolerance | Minimum pixels before a callback fires; once exceeded, it fires and the count resets. |
dragMinimum | Minimum pixels to count as dragging, so tiny touch motions don't read as intent. |
lockAxis | With touch or pointer, the first move after each press locks the direction until release. |
wheelSpeed | A wheel multiplier; -1 inverts it. |
debounce | On by default: movement adds up over each animation frame and, on each axis, the largest of wheel, scroll and touch is used. |
ignore | Elements whose events don't count. |
Per the GSAP FAQ, several Observers can share a target. The demo runs two: wheel and sideways gesture:
// Assumes a .box with overflow: hidden holding a flex .strip of four full-width slides.
const box = document.querySelector(".box");
const total = 4;
let index = 0;
let busy = false;
const canGo = (dir) => (dir > 0 ? index < total - 1 : index > 0);
function go(dir) {
if (busy || !canGo(dir)) return;
index += dir;
busy = true; // one gesture = one slide
gsap.to(".strip", { xPercent: -100 * index, duration: 0.6, ease: "power2.inOut" });
gsap.delayedCall(0.6, () => { busy = false; });
}
Observer.create({ target: box, type: "wheel", tolerance: 10,
onDown: () => go(1), onUp: () => go(-1) });
Observer.create({ target: box, type: "touch,pointer", lockAxis: true,
tolerance: 30, dragMinimum: 5,
onLeft: () => go(1), onRight: () => go(-1) });
The gesture Observer has no onUp or onDown on purpose: vertical swipes aren't its business.
Not hijacking the page scroll
Hijacking the scroll means keeping the wheel or the finger when the reader wanted to move the page. Observer alone never does it: without preventDefault it listens in passive mode, which promises the browser it will never block scrolling (that is how the Observer 3.15.0 source works). The docs use preventDefault: true in their full-screen sections demo, yet the option isn't listed in the config table.
The demo decides when to hold the wheel, and never holds a finger:
// Continues the snippet above: uses box, canGo and busy.
let lastScroll = -1e9;
document.addEventListener("scroll", () => { lastScroll = performance.now(); },
{ capture: true, passive: true });
const pageIsScrolling = () => performance.now() - lastScroll < 400;
box.addEventListener("wheel", (e) => {
const dir = Math.sign(e.deltaY);
if (!dir || pageIsScrolling()) return; // the wheel belongs to the page
if (canGo(dir) || busy) e.preventDefault(); // there is somewhere to go
}, { passive: false });
// And in the wheel Observer: onDown: () => pageIsScrolling() || go(1), same for onUp.
- Only when there is somewhere to go. The demo's own
wheellistener callspreventDefault()only if there is a slide in that direction or a step is running, even one that ends at the edge. On the first and last slides, with no step running, the wheel scrolls the page again. It passes{ passive: false }explicitly for clarity: on an element that is already the default (MDN). - The page comes first. If the page scrolled less than 400 ms ago, the wheel is the page's: the box just slid under the cursor. The
scrolllistener uses capture because a container's scroll event doesn't bubble. The cost, a choice of the demo and not of GSAP: right after a page scroll, the box waits those 400 ms. - A vertical finger belongs to the page. The box sets
touch-action: pan-y, which leaves vertical swipes to the browser, and the touch Observer only listens for the sideways gesture. - No
overscroll-behavior: contain. That property stops the scroll from passing from the box to the page once the box hits its edge, and per MDN a box withoverflow: hiddenis always at its edge. With it, neither the wheel on the last slide nor a vertical swipe moves the page.
The panel sits inside a box and only responds with the pointer over it; on this blog the page scrolls inside a container (#main-scroll-container), not the window, and the demo never touches it.
The demo: a slide panel
Nothing starts on its own. Under reduced motion, gestures, arrow keys and buttons change slides without animating, with a 0.4 s pause between steps; gsap.matchMedia() handles that, as covered in post 2.
Pointer over the box: wheel. Finger or mouse: sideways swipe. Box focused: ← → arrow keys.
Buttons and keyboard
The WCAG 2.2 accessibility guidelines ask for an alternative to dragging (criterion 2.5.7) and for everything to work from a keyboard (2.1.1). Like the carousel in post 8, the panel has "Previous" and "Next", ← → arrow keys when the box (with tabindex="0") has focus, an "N of 4" line that screen readers announce when it changes (aria-live), and the roles from the carousel pattern in the ARIA guide (APG).
ScrollTrigger.observe()
With ScrollTrigger, the plugin from post 5, already loaded, Observer.min.js isn't needed: ScrollTrigger.observe() is "identical to Observer.create()". ScrollTrigger ships it because its normalizeScroll() runs on Observer under the hood.
// Assumes ScrollTrigger is loaded, plus a .panel and the previous() and next() functions.
gsap.registerPlugin(ScrollTrigger);
ScrollTrigger.observe({ target: ".panel", type: "wheel,touch",
onUp: () => previous(), onDown: () => next() });
Common mistakes
target: windowwithpreventDefault: trueon a regular page. Scrolling is gone; the official example is a full-screen page.overscroll-behavior: containon a box withoverflow: hidden. It cuts the scroll off from the page.- One
"wheel,touch,pointer"Observer withonUpandonDown. A vertical swipe changes the slide and scrolls the page. - No pause between steps. A trackpad sends many events per gesture and skips several slides.
- A
targetthat doesn't exist. Observer throws nothing and listens to the whole page. With a selector it warns "Element not found: .panel"; with anullelement, not even that.
FAQ
Does Observer scroll anything?
No. It only reports the gesture's direction and speed; what to animate is up to the code that uses it.
Why does the wheel sometimes scroll the page over the demo?
On purpose: the demo is on the first or last slide, or the page scrolled less than 400 ms ago and the wheel belongs to it.
Conclusion
The demo rests on three pieces: one Observer per gesture, a pause so one gesture means one slide, and a single listener of its own that holds the wheel only when there is somewhere to go. A vertical finger always belongs to the page.
The rest of the series lives in the hub and posts 2, 3, 4, 5, 6, 7 and 8. Next up is post 10, on MotionPath.
References
- GSAP — Observer
- GSAP — GSAP 3.13
- unpkg — gsap@3.15.0/dist/Observer.js
- MDN — EventTarget: addEventListener()
- MDN — overscroll-behavior
- W3C — WCAG 2.2
- W3C — ARIA APG: Carousel
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment