GSAP provides a comprehensive collection of utility functions for common animation tasks, mathematical calculations, and property management. These utilities are accessible through gsap.utils and offer optimized solutions for frequent animation needs.
Essential mathematical functions for animation calculations and value manipulation.
/**
* Clamp a value between minimum and maximum bounds
* @param min - Minimum value
* @param max - Maximum value
* @param value - Value to clamp
* @returns Clamped value between min and max
*/
gsap.utils.clamp(min: number, max: number, value: number): number;
/**
* Map a value from one range to another
* @param inMin - Input range minimum
* @param inMax - Input range maximum
* @param outMin - Output range minimum
* @param outMax - Output range maximum
* @param value - Value to map
* @returns Mapped value in output range
*/
gsap.utils.mapRange(
inMin: number,
inMax: number,
outMin: number,
outMax: number,
value: number
): number;
/**
* Normalize a value to 0-1 range
* @param min - Input minimum value
* @param max - Input maximum value
* @param value - Value to normalize
* @returns Normalized value between 0 and 1
*/
gsap.utils.normalize(min: number, max: number, value: number): number;
/**
* Linear interpolation between two values
* @param start - Starting value
* @param end - Ending value
* @param progress - Progress between 0 and 1
* @returns Interpolated value
*/
gsap.utils.interpolate(start: number, end: number, progress: number): number;Usage Examples:
// Clamp mouse position to screen bounds
const clampedX = gsap.utils.clamp(0, window.innerWidth, mouseX);
// Map scroll position to rotation angle
const rotation = gsap.utils.mapRange(0, 1000, 0, 360, scrollY);
// Normalize value to percentage
const percentage = gsap.utils.normalize(0, 100, currentValue);
// Interpolate between colors (as numbers)
const midColor = gsap.utils.interpolate(0xFF0000, 0x00FF00, 0.5);Flexible random number generation with various options and configurations.
/**
* Generate random numbers with various options
* @param min - Minimum value (or array of values to choose from)
* @param max - Maximum value
* @param snap - Snap increment (e.g., 5 to snap to multiples of 5)
* @param returnFunction - Return a function instead of a value
* @returns Random number or random function
*/
gsap.utils.random(
min: number | any[],
max?: number,
snap?: number,
returnFunction?: boolean
): number | Function;Usage Examples:
// Basic random number
const randomX = gsap.utils.random(0, 100);
// Random from array
const randomColor = gsap.utils.random(["red", "blue", "green"]);
// Snapped random (multiples of 10)
const snappedRandom = gsap.utils.random(0, 100, 10);
// Random function for repeated use
const randomizer = gsap.utils.random(0, 360, 1, true);
console.log(randomizer()); // Different number each call
// Use in animations
gsap.to(".box", {
x: gsap.utils.random(0, 500),
y: gsap.utils.random(0, 300),
rotation: gsap.utils.random(0, 360)
});Snap values to specific increments or closest values in an array.
/**
* Snap values to increments or specific values
* @param snapConfig - Number for increment, or array of values to snap to
* @param value - Value to snap (omit to return snap function)
* @returns Snapped value or snap function
*/
gsap.utils.snap(snapConfig: number | number[], value?: number): number | Function;Usage Examples:
// Snap to increments of 10
const snapped = gsap.utils.snap(10, 47); // Returns 50
// Snap to specific values
const snapToGrid = gsap.utils.snap([0, 25, 50, 75, 100], 42); // Returns 50
// Create snap function for reuse
const snapTo5 = gsap.utils.snap(5);
console.log(snapTo5(17)); // Returns 15
console.log(snapTo5(23)); // Returns 25
// Use in Draggable
Draggable.create(".box", {
bounds: ".container",
onDrag: function() {
this.x = gsap.utils.snap(20, this.x); // Snap to 20px grid
}
});Functions for working with arrays and converting values to arrays.
/**
* Convert value to array format
* @param value - Value to convert (selector, NodeList, single element, etc.)
* @param scope - Optional scope to query within
* @param leaveStrings - Don't convert strings to elements
* @returns Array of elements or values
*/
gsap.utils.toArray(value: any, scope?: Element, leaveStrings?: boolean): any[];
/**
* Randomly shuffle array elements
* @param array - Array to shuffle
* @returns Shuffled array (modifies original)
*/
gsap.utils.shuffle(array: any[]): any[];
/**
* Wrap array access (handles negative indices and overflow)
* @param values - Array of values
* @param index - Index to access (can be negative or > array length)
* @returns Value at wrapped index
*/
gsap.utils.wrap(values: any[], index?: number): any | Function;
/**
* Wrap with yoyo behavior (bounce back and forth)
* @param values - Array of values
* @param index - Index to access
* @returns Value at yoyo-wrapped index
*/
gsap.utils.wrapYoyo(values: any[], index?: number): any | Function;Usage Examples:
// Convert various formats to arrays
const elements = gsap.utils.toArray(".box"); // NodeList to array
const mixed = gsap.utils.toArray([".box1", document.getElementById("box2")]);
// Shuffle array
const colors = ["red", "blue", "green", "yellow"];
gsap.utils.shuffle(colors); // Randomly reorder
// Wrap array access
const values = [10, 20, 30, 40];
const wrapper = gsap.utils.wrap(values);
console.log(wrapper(5)); // 20 (wraps to index 1)
console.log(wrapper(-1)); // 40 (wraps to last element)
// Yoyo wrapping (bounce effect)
const yoyoWrapper = gsap.utils.wrapYoyo(values);
console.log(yoyoWrapper(5)); // 30 (bounces back)Functions for distributing values across multiple targets with various patterns.
/**
* Distribute values across an array based on configuration
* @param config - Distribution configuration
* @returns Function that calculates distributed values
*/
gsap.utils.distribute(config: gsap.utils.DistributeConfig): Function;
interface DistributeConfig {
base?: number; // Base value to start from
amount?: number; // Total amount to distribute
from?: "start" | "center" | "end" | "edges" | "random" | number;
grid?: [number, number]; // Grid dimensions [columns, rows]
axis?: "x" | "y"; // Primary axis for grid distribution
ease?: string | Function; // Easing function for distribution
}Usage Examples:
// Distribute rotation values
gsap.to(".box", {
duration: 1,
rotation: gsap.utils.distribute({
base: 0,
amount: 360,
from: "center"
})
});
// Grid-based distribution
gsap.to(".grid-item", {
duration: 1,
scale: gsap.utils.distribute({
base: 1,
amount: 0.5,
grid: [5, 5],
from: "center",
ease: "power2.out"
})
});
// Edge-based distribution
gsap.to(".element", {
delay: gsap.utils.distribute({
base: 0,
amount: 2,
from: "edges"
})
});Functions for working with element properties and DOM queries.
/**
* Get computed property value from an element
* @param target - Element to query
* @param property - CSS property name
* @param unit - Optional unit to return value in
* @returns Property value as string
*/
gsap.getProperty(target: Element, property: string, unit?: string): string;
/**
* Create optimized property setter function
* @param targets - Elements to create setter for
* @param property - Property to set
* @param unit - Optional unit for values
* @returns Fast setter function
*/
gsap.quickSetter(targets: gsap.TweenTarget, property: string, unit?: string): Function;
/**
* Create reusable animation function
* @param target - Element to animate
* @param property - Property to animate
* @param vars - Animation configuration
* @returns Function that animates to specified values
*/
gsap.quickTo(target: Element, property: string, vars?: gsap.TweenVars): Function;Usage Examples:
// Get property values
const currentX = gsap.getProperty(".box", "x");
const opacity = gsap.getProperty("#element", "opacity");
// Quick setter for performance
const setX = gsap.quickSetter(".box", "x", "px");
setX(100); // Much faster than gsap.set for repeated calls
// Quick animation function
const animateX = gsap.quickTo(".box", "x", { duration: 0.3, ease: "power2.out" });
animateX(100); // Animate to x: 100
animateX(200); // Animate to x: 200 (interrupts previous)Functions for working with strings, colors, and CSS values.
/**
* Split color string into RGB/HSL components
* @param color - Color string to parse
* @param hsl - Return HSL instead of RGB
* @returns Array of color components
*/
gsap.utils.splitColor(color: string, hsl?: boolean): number[];
/**
* Extract unit from a CSS value string
* @param value - CSS value with unit
* @returns Unit string (e.g., "px", "%", "em")
*/
gsap.utils.getUnit(value: string): string;
/**
* Get vendor-prefixed CSS property name
* @param property - CSS property name
* @returns Prefixed property name if needed
*/
gsap.utils.checkPrefix(property: string): string;Usage Examples:
// Parse colors
const rgb = gsap.utils.splitColor("#FF0000"); // [255, 0, 0]
const hsl = gsap.utils.splitColor("rgb(255, 0, 0)", true); // [0, 100, 50]
// Extract units
const unit = gsap.utils.getUnit("100px"); // "px"
const percentUnit = gsap.utils.getUnit("50%"); // "%"
// Check for vendor prefixes
const transform = gsap.utils.checkPrefix("transform"); // May return "webkitTransform" in older browsersHigher-order functions for creating reusable utility patterns.
/**
* Chain multiple functions together (pipe pattern)
* @param functions - Functions to chain
* @returns Function that pipes value through all functions
*/
gsap.utils.pipe(...functions: Function[]): Function;
/**
* Add units to function output
* @param func - Function to wrap
* @param unit - Unit to append to return values
* @returns Function that appends units to output
*/
gsap.utils.unitize(func: Function, unit?: string): Function;
/**
* Create scoped selector function
* @param scope - Element to scope queries within
* @returns Selector function scoped to the element
*/
gsap.utils.selector(scope: Element): Function;Usage Examples:
// Pipe functions together
const processValue = gsap.utils.pipe(
(x) => x * 2, // Double the value
(x) => x + 10, // Add 10
(x) => Math.round(x) // Round result
);
console.log(processValue(5.3)); // 21
// Add units to function output
const randomWithPx = gsap.utils.unitize(gsap.utils.random, "px");
console.log(randomWithPx(0, 100)); // "47px" (example)
// Scoped selector
const containerSelector = gsap.utils.selector(".container");
const boxes = containerSelector(".box"); // Only finds .box elements within .container