Capítulo 167 de 411

Chapter 167: Simple FLIP (Helper)

Core Idea

A lightweight helper implementing the FLIP technique (First-Last-Invert-Play) for animating elements to their new position after a DOM change, for cases too simple to justify the full Flip plugin.

Key Concepts

  • Signature: flip(elements, changeFunc, vars) — records each element's bounding box, calls changeFunc() to perform the actual DOM change, then tweens x/y from the old position to the new one.
  • vars supports duration, stagger, ease, onComplete, delay.
  • Returns a Timeline containing all the resulting animations.
  • Tracks an internal _flip reference per element so overlapping calls fast-forward any in-progress FLIP first.

Code Examples

function flip(elements, changeFunc, vars) {
  elements = gsap.utils.toArray(elements);
  vars = vars || {};
  let tl = gsap.timeline({ onComplete: vars.onComplete, delay: vars.delay || 0 }),
    bounds = elements.map((el) => el.getBoundingClientRect()), copy = {}, p;
  elements.forEach((el) => { el._flip && el._flip.progress(1); el._flip = tl; });
  changeFunc();
  for (p in vars) if (p !== "onComplete" && p !== "delay") copy[p] = vars[p];
  copy.x = (i, element) => "+=" + (bounds[i].left - element.getBoundingClientRect().left);
  copy.y = (i, element) => "+=" + (bounds[i].top - element.getBoundingClientRect().top);
  return tl.from(elements, copy);
}
  • What it demonstrates: measure-before, mutate, then animate-from-the-old-position — the core FLIP loop, without any of the more advanced features of the official plugin.

Anti-patterns

  • Using this for complex layouts (nested/resizing elements, absolute positioning changes): the full Flip plugin handles those correctly; this helper only compensates simple x/y translation.

Connects To

  • Flip plugin: the full-featured equivalent for anything beyond basic position changes.