Capítulo 351 de 411

Chapter 351: ScrollTrigger.batch

Core Idea

Creates 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.

Key Concepts

  • triggers: Selector text | Array

  • vars: Object

  • batchMax [Integer | Function] - The maximum number of elements that should be allowed in each batch. When a batch is full, it will immediately fire its callback and begin collecting the next batch and if that fills immediately as well it will fire immediately. So if, for example, you set batchMax: 3 and then 9 elements all enter the viewport at roughly the same time, 3 batches would be created, thus the onEnter callback would get fired 3 times in quick succession (not waiting for the interval to elapse). If you have a responsive layout that may require changing of the batchMax when the page resizes, you can use a function instead that returns an Integer. That will get called whenever ScrollTrigger fires a "refresh" (which occurs when the viewport resizes, when an inactive tab becomes active, etc.). Like batchMax: () => { ...your logic here... return integer }
  • interval [Number] - The maximum amount of time (in seconds) to spend collecting each batch. Once a callback of a certain type is called, the timer begins, and then the batch will complete when it elapses or when the batchMax is reached (whichever is first).

Code Examples

ScrollTrigger.batch(".box", {
  onEnter: (elements, triggers) => {
    gsap.to(elements, { opacity: 1, stagger: 0.15 });
    console.log(elements.length, "elements entered");
  },
  onLeave: (elements, triggers) => {
    gsap.to(elements, { opacity: 0, stagger: 0.15 });
    console.log(elements.length, "elements left");
  },
});
  • What it demonstrates: typical usage of ScrollTrigger.batch in a GSAP animation.

Key Takeaways

  1. triggers: Selector text | Array

  2. vars: Object

  3. batchMax [Integer | Function] - The maximum number of elements that should be allowed in each batch.
  4. interval [Number] - The maximum amount of time (in seconds) to spend collecting each batch.

Connects To