Skip to content

Responsive Animations

Managing animations across different screen sizes requires careful cleanup.

AnimX.responsive() links animations to specific CSS media queries. When the screen size changes, it automatically stops old animations, cleans up their styles, and starts the correct new animations.


1. Breakpoint Contexts

Create a responsive context using AnimX.responsive(), and add standard CSS media queries to define your breakpoints.

TIP

Use the device icons in the LivePreview control bar below to test the 600px and 400px breakpoint thresholds.

Test viewport breakpoints using the interactive controls
60 FPS

When the screen size changes to match a new breakpoint, any animations from the old breakpoint are stopped and cleaned up automatically.

IMPORTANT

You must register your animations by calling context.add(tween) inside your handler. This enables the automatic cleanup when the screen size changes. If you forget this, your animations will conflict with each other.


2. Custom Cleanup

If you need to do manual cleanup (like removing event listeners), you can return a cleanup function from your handler.

Toggle breakpoints to observe event listener cleanup in the console
60 FPS

When the screen size no longer matches your media query, the returned cleanup function will run, safely removing your event listeners.


API Reference

AnimX.responsive()

Creates and returns a new responsive context.

Instance Methods

MethodDescription
add(query, handler)Registers a new breakpoint. The handler runs whenever the screen matches the query.
remove(query)Removes a specific media query and immediately cleans up its animations and styles.
revert()Removes all registered media queries and cleans up everything. Works exactly like kill().
kill()Identical to revert().

The handler Callback

When you call ctx.add(query, handler), your handler function receives a context object as its only argument.

js
ctx.add('(min-width: 1024px)', (context) => {
  const tween = AnimX.animate('.box', { x: 200 })
  
  // 1. Register tweens so they revert automatically
  context.add(tween)
  
  // 2. (Optional) Return custom cleanup logic for event listeners
  return () => {
    // Custom cleanup code runs when the breakpoint stops matching
  }
})

Context Methods

MethodDescription
context.add(tween)Registers an animation with this breakpoint. When the screen size changes, AnimX will automatically stop the animation and clean up its styles.
context.revert()Manually forces cleanup for this specific breakpoint (stops its animations and runs your cleanup function).