Capítulo 331 de 411

Chapter 331: ScrollTrigger

Core Idea

added in v3.3.0

Key Concepts

  • Link any animation to a particular element so that it only plays when that element is in the viewport. This improves performance and ensures that your beautiful animations actually get seen!
  • ScrollTriggers can perform an actions on an animation (play, pause, resume, restart, reverse, complete, reset) when entering/leaving the defined area or link it directly to the scrollbar so that it acts like a scrubber (scrub: true).
  • Soften the link between the animation and the the scrollbar so that takes a certain amount of time to "catch up", like scrub: 1 would take one second to catch up.
  • Integrated with ScrollSmoother, GreenSock's smooth-scrolling tool built on native scroll technology (members-only benefit).
  • Snap to certain points in the animation based on velocity. In fact, you can getVelocity() of the scrolling anytime. Snap to the closest label in a timeline or progress value in an Array, or run your own custom function-based logic for snapping
  • Embed scroll triggers directly into any GSAP animation (including timelines) or create standalone instances and tap into the rich callback system to do anything you want.
  • Advanced pinning capabilities can lock an element in place between certain scroll positions. Padding is automatically added to push other elements down accordingly, so they catch up when the element gets unpinned (disable this with pinSpacing: false). You can even pin the same element multiple times at different points.
  • Incredible flexibility for defining scroll positions - like "start when the center of this element hits the center of the viewport, and end when the bottom of that other element hits the bottom of the viewport", use keywords (top, center, bottom, left, right), percentages, pixels, or even relative values like "+=300px". Once you get the hang of the syntax, it's remarkably intuitive.

Code Examples

gsap.registerPlugin(ScrollTrigger)
  • What it demonstrates: typical usage of ScrollTrigger in a GSAP animation.

Reference Tables

#### .animation : Tween | Timeline | undefined[read-only] The Tween or Timeline associated with the ScrollTrigger instance (if any).
#### .direction : Number[read-only] Reflects the moment-by-moment direction of scrolling where 1 is forward and -1 is backward.
#### .end : Number[read-only] The ScrollTrigger's ending scroll position (numeric, in pixels).
#### .isActive : Boolean[read-only] Only true if the scroll position is between the start and end positions of the ScrollTrigger instance.
#### ScrollTrigger.isTouch : NumberA way to discern the touch capabilities of the current device - 0 is mouse/pointer only (no touch), 1 is touch-only, 2 accommodates both.
#### .pin : Element | undefined[read-only] The pin element (if one was defined). If selector text was used, like ".pin", the pin will be the element itself (not selector text)
#### progress : Number[read-only] The overall progress of the ScrollTrigger instance where 0 is at the start, 0.5 is in the middle, and 1 is at the end.
#### scroller : Element | window[read-only] The scroller element (or window) associated with the ScrollTrigger. It's the thing whose scrollbar is linked to the ScrollTrigger. By default, it's the window (viewport).
#### start : Number[read-only] The ScrollTrigger's starting scroll position (numeric, in pixels).
#### .trigger : Element | undefined[read-only] The trigger element (if one was defined). If selector text was used, like ".trigger", the trigger will be the element itself (not selector text)
#### .vars : Object[read-only] The vars configuration object used to create the ScrollTrigger instance
#### .disable( revert:boolean, allowAnimation:Boolean )Disables the ScrollTrigger instance, immediately unpinning and restoring any pin-related changes made to the DOM by ScrollTrigger.
#### .enable( reset:Boolean )Enables the ScrollTrigger instance
#### .getTween( snap:Boolean ) : TweenReturns the scrub tween (default) or the snapping tween (getTween(true))
#### .getVelocity( ) : NumberGets the scroll velocity in pixels-per-second
#### .kill( revert:boolean, allowAnimation:Boolean )Kills the ScrollTrigger instance, immediately unpinning and restoring any pin-related changes made to the DOM by ScrollTrigger and removing all scroll-related listeners, etc. so that the instance is eligible for garbage collection. If you only want to temporarily disable the ScrollTrigger, use the disable() method instead.
#### .labelToScroll( label:String ) : NumberConverts a timeline label into the associated scroll position (only applicable to ScrollTriggers whose "animation" is a timeline)
#### .next( ) : ScrollTrigger instanceReturns the next ScrollTrigger in the refresh order.
#### .previous( ) : ScrollTrigger instanceReturns the previous ScrollTrigger in the refresh order.
#### .refresh()Forces the ScrollTrigger instance to re-calculate its start and end values (the scroll positions where it'll be activated).
#### .scroll( position:Number ) : Number | nullGets/Sets the scroll position of the associated scroller (numeric).
#### ScrollTrigger.addEventListener( type:String, callback:Function ) : nullAdd a listener for any of the following events: "scrollStart", "scrollEnd", "refreshInit", "revert", "matchMedia", or"refresh" which get dispatched globally when any such ScrollTrigger-related event occurs (it is not tied to a particular instance).
#### ScrollTrigger.batch( triggers:Selector text | Array, vars:Object ) : ArrayCreates a coordinated group of ScrollTriggers (one for each target element) that batch their callbacks (onEnter, onLeave, etc.) within a certain interval, delivering a neat Array so that you can easily do something like create a staggered animation of all the elements that enter the viewport around the same time.
#### ScrollTrigger.clearMatchMedia( query:String )
#### ScrollTrigger.clearScrollMemory( scrollRestoration:String )Clears any recorded scroll positions in ScrollTrigger so that no scroll positions get restored after a refresh(). Normally, this isn't necessary but in some frameworks that handle routing in unconventional ways, it can be useful.
#### ScrollTrigger.config( vars:Object )Allows you to configure certain global behaviors of ScrollTrigger like limitCallbacks
#### ScrollTrigger.create( vars:Object ) : ScrollTriggerCreates a standalone ScrollTrigger instance
#### ScrollTrigger.defaults( config:Object ) : nullAllows you to set the default values that apply to every ScrollTrigger upon creation, like toggleActions, markers, etc.
#### ScrollTrigger.getAll( ) : ArrayReturns an Array of all ScrollTrigger instances
#### ScrollTrigger.getById( id:String ) : ScrollTriggerReturns the ScrollTrigger that was assigned the corresponding id
#### ScrollTrigger.isInViewport( Element:Element | String, proportion:Number, horizontal:Boolean ) : BooleanReturns true if the element is in the viewport. You can optionally specify a minimum proportion, like ScrollTrigger.isInViewport(element, 0.2) would only return true if at least 20% of the element is in the viewport.
#### ScrollTrigger.isScrolling( ) : BooleanIndicates whether or not any ScrollTrigger-related scroller is in the process of scrolling.
#### ScrollTrigger.killAll( ) ;Immediately calls kill() on all ScrollTriggers (except the main ScrollSmoother one if it exists).
#### ScrollTrigger.matchMedia( vars:Object )[DEPRECATED] Allows you to set up ScrollTriggers that only apply to certain viewport sizes (using media queries).
#### ScrollTrigger.maxScroll( scroller:Element | window, horizontal:Boolean ) : NumberA utility function for getting the maximum scroll value for a particular element/scroller. For example, if the element/scroller is 500px tall and contains 800px of content, maxScroll() would return 300.
#### ScrollTrigger.normalizeScroll( normalize:Boolean | Object ) : ScrollObserver | nullForces scrolling to be done on the JavaScript thread, ensuring screen updates are synchronized and the address bar doesn't show/hide on [most] mobile devices.
#### ScrollTrigger.observe( config:Object ) : ObserverSuper-flexible, unified way to sense meaningful events across all (touch/mouse/pointer) devices without wrestling with all the implementation details. Trigger simple callbacks like onUp, onDown, onLeft, onRight, onChange, onHover, onDrag, etc. Functionally identical to Observer.create()
#### ScrollTrigger.positionInViewport( element:Element | String, referencePoint:String | Number, horizontal:Boolean ) : NumberReturns a normalized value representing the element's position in relation to the viewport where 0 is at the top of the viewport, 0.5 is in the center, and 1 is at the bottom. So, for example, if the top of the element is 80% down from the top of the viewport, the following code would return 0.8: ScrollTrigger.positionInViewport(element, "top");
#### ScrollTrigger.refresh( safe:Boolean )Recalculates the positioning of all of the ScrollTriggers on the page; this typically happens automatically when the window/scroller resizes but you can force it by calling ScrollTrigger.refresh()
#### ScrollTrigger.removeEventListener( type:String, callback:Function ) : nullRemoves an event listener
#### ScrollTrigger.saveStyles( targets:String | Element | Array )Internally records the current inline CSS styles for the given elements so that when ScrollTrigger reverts (typically for a refresh() or matchMedia() change) those elements will be reverted accordingly even if they had animations that added/changed inline styles. Think of it like taking a snapshot of the inline CSS and telling ScrollTrigger "re-apply these inline styles only and dump all others when you revert internally".
#### ScrollTrigger.scrollerProxy( scroller:String | Element, vars:Object )Allows you to hijack the scrollTop and/or scrollLeft getters/setters for a particular scroller element so that you can implement things like smooth scrolling or other custom effects.
#### ScrollTrigger.snapDirectional( incrementOrArray:Number | Array ) : FunctionReturns a snapping function to which you can feed any value to snap, along with a direction where 1 is forward (greater than) and -1 is backward (less than).
#### ScrollTrigger.sort( func:Function ) : ArraySorts the internal Array of ScrollTrigger instances to control the order in which they refresh() (calculate their start/end values).
#### ScrollTrigger.update( )Checks where the scrollbar is and updates all ScrollTrigger instances' progress and direction values accordingly, controls the animation (if necessary) and fires the appropriate callbacks.

Key Takeaways

  1. Link any animation to a particular element so that it only plays when that element is in the viewport.
  2. ScrollTriggers can perform an actions on an animation (play, pause, resume, restart, reverse, complete, reset) when entering/leaving the…
  3. Soften the link between the animation and the the scrollbar so that takes a certain amount of time to "catch up", like scrub: 1 would…
  4. Integrated with ScrollSmoother, GreenSock's smooth-scrolling tool built on native scroll…
  5. Snap to certain points in the animation based on velocity.

Connects To