Capítulo 22 de 411

Chapter 22: gsap.matchMedia()

Core Idea

gsap.matchMedia() (added in 3.11) ties setup functions to CSS media queries, running them when a query starts matching and automatically cleaning up (via an internal gsap.context()) when it stops matching.

Key Concepts

  • mm.add(query, setupFn): registers a function that runs only while query matches; return a cleanup function from it for custom teardown logic.
  • Automatic revert: any GSAP animations/ScrollTriggers created inside the setup function are automatically reverted when the query stops matching, no manual bookkeeping required.

Code Examples

let mm = gsap.matchMedia();

mm.add("(min-width: 800px)", () => {
  gsap.to(".box", { x: 300 });
  ScrollTrigger.create({ trigger: ".box", start: "top center" });

  return () => {
    // optional custom cleanup when it stops matching
  };
});
  • What it demonstrates: defining desktop-only animation setup that both activates and reverts automatically as the viewport crosses the 800px breakpoint.

Key Takeaways

  1. This is the standard way to build responsive, breakpoint-aware animation without manually tracking window resize events.
  2. It supersedes hand-rolled matchMedia + manual revert logic — cleanup is handled for you.

Connects To

  • gsap.matchMediaRefresh(): forces all matchMedia instances to re-evaluate immediately.
  • gsap.context(): the underlying cleanup mechanism matchMedia uses internally.