Capítulo 169 de 411

Chapter 169: Directional Snapping (Helper)

Core Idea

gsap.utils.snap() always snaps to the closest increment/value; this helper adds a direction argument so a value snaps strictly to the next greater or next lesser increment instead.

Key Concepts

  • Wraps gsap.utils.snap(); accepts either a numeric increment or a sorted array of allowed values.
  • Direction argument: 1 = snap to the closest value greater than the input, -1 = closest lesser, falsy = normal closest-match snap.
  • Subtracts a tiny epsilon before searching upward to avoid repeated re-snapping caused by float rounding.

Code Examples

let snap = gsap.utils.snap(5);
snap(2);   // 0  (closest)
snap(19);  // 20 (closest)

let dirSnap = getDirectionalSnapFunc(5);
dirSnap(19, 1);  // 20 (next greater)
dirSnap(19, -1); // 15 (next lesser)
  • What it demonstrates: contrast between gsap.utils.snap()'s "closest" behavior and this helper's directional variant.

Key Takeaways

  1. Useful for carousels/sliders where you want scroll momentum to always land on the next slide in the drag direction, not just the closest.

Connects To

  • gsap.utils.snap(): the base utility this helper wraps.