ScrollTrigger getTween() and getVelocity()
- Learn how to access ScrollTriggerโs internal tween and measure scroll speed using getTween() and getVelocity().
Introduction
In GreenSock GSAP, ScrollTrigger provides advanced methods to control animations based on scroll.
Two important helper methods are:
-
getTween() โ access the animation linked to ScrollTrigger
-
getVelocity() โ detect how fast the user is scrolling
These are commonly used in:
-
Scroll-based animations
-
Momentum effects
-
Speed-based UI reactions
-
Advanced interactive websites
-
Basic Concept
What is getTween()?
-
Returns the GSAP tween controlled by ScrollTrigger
-
Allows you to pause, play, reverse, or inspect the animation
What is getVelocity()?
-
Returns the scroll speed
-
Positive value โ scrolling down
-
Negative value โ scrolling up
๐ Think of it as a scroll speed meter
-
getTween()
scrollTrigger.getTween();
getVelocity()
scrollTrigger.getVelocity();
Parameters / Options
Method What it Returns Notes getTween() GSAP Tween Only if animation exists getVelocity() Number Pixels per second Positive value Scroll down โ Negative value Scroll up โ
Using getTween()
ScrollTrigger.create({
trigger: ".box",
start: "top center",
animation: gsap.to(".box", { x: 300 }),
onEnter(self) {
const tween = self.getTween();
tween.pause();
}
});
Detect Scroll Speed (getVelocity)
ScrollTrigger.create({
trigger: ".section",
onUpdate(self) {
console.log(self.getVelocity());
}
});
Change Animation Based on Scroll Speed
ScrollTrigger.create({
onUpdate(self) {
if (self.getVelocity() > 500) {
gsap.to(".box", { scale: 1.2 });
} else {
gsap.to(".box", { scale: 1 });
}
}
});
Common Mistakes
-
โ Calling getTween() without animation
โ It works only when ScrollTrigger has an animation -
โ Using getVelocity() outside callbacks
โ Always use insideonUpdate -
โ Expecting getVelocity() to return direction text
โ It returns a number, not a string -
โ Overusing heavy logic inside onUpdate
โ Keep code lightweight for performance
-
Best Practices
-
Use getVelocity() for subtle UI reactions
-
Avoid heavy DOM updates on every scroll
-
Cache values if possible
-
Combine with
scrubfor smooth effects
-
Comparison
Method Purpose Use Case getTween() Access animation Control / inspect tween getVelocity() Scroll speed Momentum / direction self.progress Scroll progress Timeline sync self.direction Scroll direction Simple up/down