After Effects Expressions.

start typing a keyword to search the free database.

Animate A Property With Keyframe

Animate the porperty of a layer using sliders and keyframes.

  • Add to a property e.g. position
  • add 3 sliders to that layer, "X Amplitude Control", "Y Amplitude Control" & "Decay Control", these can be keyframed
  • add keyframes to the layer to trigger the expressions effects.

  var n = 0;  
  var t = 0;  
  
  if (marker.numKeys > 0) {  
      n = marker.nearestKey(time).index;  
      if (marker.key(n).time > time) n--;  
  }  
  if (n > 0) t = time - marker.key(n).time;  
  
  // Slider controls
  var xAmp = effect("X Amplitude Control")("Slider"); // Control for X amplitude
  var yAmp = effect("Y Amplitude Control")("Slider"); // Control for Y amplitude
  var decay = effect("Decay Control")("Slider"); // Control for decay rate
  var freq = 5; // Frequency remains constant
  
  var angle = freq * 2 * Math.PI * t;
  var xScaleFact = (100 + xAmp * Math.sin(angle) / Math.exp(decay * t)) / 100;
  var yScaleFact = (100 + yAmp * Math.sin(angle) / Math.exp(decay * t)) / 100;
  
  [value[0] * xScaleFact, value[1] / yScaleFact];

download project example

One Layer Positioned Between Another

Quick way to attach layers and add secondary animation.
*add to the position property.

  ( thisComp.layer(1).position + thisComp.layer(2).position ) / 2

download project example

Delay Layers Position

Quick way to attach layers and add secondary animation.
*add to the position property.

  var delay = -5; // Sets a delay amount in frames 
  var multiplyDelay = delay * ( index - parent.index )

  parent.fromComp( toComp( anchorPoint, time - framesToTime( multiplyDelay ) ) );

download project example

Source Text Rolls Through Random Characters.

This expressions allows text keyframes to automatically roll through user defined characters.
*add to the source property of the text layer.

  // Initial text values from the keyframes
  var startText = text.sourceText.key(1).value;
  var endText = text.sourceText.key(2).value;
  
  // Animation parameters
  var animationDuration = 0.25; // Duration for each character animation
  var characterDelay = 0.05;   // Time between character animations
  var startOffset = inPoint + 1; // When to start animating
  var fps = 5;  // Speed of random characters
  
  // Time-related variables
  var timeSinceOffset = time - startOffset; // Time elapsed since animation started
  var maxLength = Math.max(startText.length, endText.length); // Maximum length between start and end text
  
  // Function to generate a random character based on a seed
  var getRandomCharacter = function(seed) {
      var chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"; // change to any characters you want to use
      seedRandom(Math.floor(time * fps) + seed, true);  // Seed the random generator
      return chars.charAt(Math.floor(random(0, chars.length))); // Return a random character
  }
  
  // Build the output string based on time and animation parameters
  var result = "";
  
  for (var i = 0; i < maxLength; i++) {
      var delayTime = characterDelay * i; // Delay time for each character animation
      
      if (timeSinceOffset < delayTime) {
          // Before the character should animate, show the start text
          result += startText.charAt(i) || ""; // Fallback in case the text lengths are different
      } else if (timeSinceOffset < delayTime + animationDuration) {
          // During the animation duration, show random characters
          result += getRandomCharacter(i);
      } else {
          // After animation, show the end text
          result += endText.charAt(i) || ""; // Fallback in case the text lengths are different
      }
  }
  
  result; // Return the final animated string

download project example

Elastic Connect

Quick way to attach layers and add secondary animation.
*add to the position property.

  var restLength = 20; // Desired distance between leader and follower
  var damp = 0.95; // Damping to smooth the motion
  var leader = thisComp.layer("leader"); // Reference to leader layer
  var fDur = thisComp.frameDuration; // Frame duration
  var p2 = position.valueAtTime(0); // Start position of follower
  var v2 = 0; // Initial velocity

  for (var t = 0; t <= time; t += fDur) {
  var delta = p2 - leader.transform.position.valueAtTime(t); // Offset vector
  var a = normalize(delta) * ((length(delta) - restLength) * fDur * 2); // Acceleration
  v2 = (v2 - a) * damp; // Update velocity
  p2 += v2; // Update position
  }

// Output final position
  p2;

download project example

Spirograph Patterns

Jumps from a random point in the layer each specified period.
*add to the time remapping of a layer, adjust the segment Duration for a longer playback period.

  rad1 = 87; //radius 1
  rad2 = 30; // radius 2
  offset = 70;
  v = 3; //velocity
  s = 2; //scale
  x = (rad1+rad2)*Math.cos(time*v)-(rad2+offset)*Math.cos((rad1+rad2)*time*v/rad2);
  y= (rad1+rad2)*Math.sin(time*v)-(rad2+offset)*Math.sin((rad1+rad2)*time*v/rad2);
  
  [s*x+thisComp.width/2,s*y+thisComp.height/2];

Simulated timeline scrubbing with some limited playback

Jumps and plays from a random point in the layer each specified period.
*add to the time remapping of a layer, adjust the segment Duration for a longer playback period.

  // Define variables
  var tmin = 0.125;
  var tmax = 0.25;
  var initialSeed = 11;
  var end = 0;
  var j = initialSeed;
  var start = 0;
  
  // Loop to determine the time range
  while (time >= end) {
      j += 1; // Increment j
      seedRandom(j, true); // Set random seed
      start = end; // Update start to previous end
      end += random(tmin, tmax); // Increment end by a random value in the range [tmin, tmax]
  }
  
  // Generate targetTime and other variables
  var targetTime = random(thisComp.duration);
  seedRandom(j - 1, true); // Reset random seed for the previous value
  var dummy = random(); // Generate a dummy random value
  var oldTime = random(thisComp.duration); // Generate a random old time
  
  // Map the time using linear interpolation
  linear(time, start, end, oldTime, targetTime);

Simulated timeline scrubbing

Jumps from a random point in the layer each specified period.
*add to the time remapping of a layer, adjust the segment Duration for a longer playback period.

  n = 10; // hold frames
  f = timeToFrames(time);
  period = Math.floor(f/n);
  seedRandom(period,true);
  if (numKeys >1) {
    random (inPoint, key(numKeys).time-thisComp.frameDuration);
  } else {
    value
  }

Time Remapping, jump cut style

jumps and plays from a random point in the layer each specified period.
*add to the time remapping of a layer, adjust the segment Duration for a longer playback period.

  segDur = 0.5; //segment Duration
  minVal = inPoint;
  maxVal = outPoint-segDur;
  seed = Math.floor(time/segDur);
  segStart = seed*segDur;
  seedRandom(seed,true);
  startVal = random(minVal,maxVal);
  endVal = startVal+segDur;
  linear (time,segStart, segStart+segDur, startVal, endVal);

Skip Frames

Allows specified layers to skip frames indicidually druting playback and render.
*add to the time remapping of a layer.

  a=2;
  b=2;
  f=timeToFrames();
  p=Math.floor(f/b);

  framesToTime(p*a);

download project example

Conditional Trigger Based on Time

Triggers an animation at a specific time and can be used to automate various events.
*add to various properties.

  triggerTime = 2; // triggers effect in  x seconds

  if (time > triggerTime) {
  100;
  } else {
  0;
  }

download project example

Check if Layer is On-Screen (Visibility Check)

Changes a layers opacity ON / OFF based on its position within the screen boundaries.
*add to a layers opacity.

  top = thisComp.height;
  bottom = 0;
  left = 0;
  right = thisComp.width;
  x = position[0];
  y = position[1];
  
  if (x > left && x < right && y > bottom && y < top) {
  100;
  } else {
  0;
  };
download project example

Value Based on a Layers Interaction

Change a property (opacity) based on the proximity of a secified layer.
*add to layers opacity and add a object and call this "collider". The interaction between the 2 will change the opacity.

  colliderPos = thisComp.layer("collider").position; //assign a layer to be the collider
  distance = length(colliderPos, position);
  maxDistance = 300; // max distance for full visibility defined by colliders position
  
  linear(distance, 0, maxDistance, 100, 0);

download project example

Automatic Counter using Text with Easing

*add to the text source property.

  var startValue = 0;
  var endValue = 100;
  var duration = 3; // Duration in seconds of the effect
  
  ease(time, 0, duration, startValue, endValue).toFixed(0);
download project example

Responsive Text Width Based on Screen Size

Automatically adjusts text size based on screen width, making the text responsive.
*add to the scale property of a text layer.

  minFontSize = 20;
  maxFontSize = 100;
  maxWidth = thisComp.width;
    
  scaleFactor = linear(sourceRectAtTime().width, 0, maxWidth, maxFontSize, minFontSize);
  [scaleFactor, scaleFactor];
download project example

Sinusoidal Pulse with Decay

Can be used on various properties.
*add to opacity property.

  frequency = 3;  // number of pulses per second
  decay = 0.5;    // decay rate

  pulse = Math.sin(time * frequency * Math.PI * 2) * Math.exp(-decay * time);
  100 + pulse * 20; // adjust these values to control pulse intensity and scale
download project example

Blur Based on Speed

Adds a blur based on the speed of the layer’s movement.
*Apply to a layers blur effect.

  speed = length(position.velocity);
  maxBlur = 20;  // Max blur amount

  linear(speed, 0, 300, 0, maxBlur); // Adjust 300 to match max speed
download project example

Swaying or Bobbing Effect (Natural Swing)

Mimics the natural swaying of objects like leaves or pendulums.
*swings from an achor point.

  swayAngle = 10; // Maximum sway angle
  swaySpeed = 2;  // Frequency of sway

  swayAngle * Math.sin(time * swaySpeed);

download project example

Randomized Flicker

  flickerRate = 5; // Flickers per second
  
  seedRandom(time * flickerRate, true);
  if (random(0, 1) > 0.5) {
  100;
  } else {
  0;
  }

download project example

Time-Based Layer Cloning with Fade-Out Effect

Adds an automatic fade-out effect based on time.

  cloneInterval = 0.1; // Interval between clones
  fadeDuration = 1;    // How long each clone fades out
  delay = cloneInterval * (index - 1);

  cloneOpacity = linear(time - delay, 0, fadeDuration, 100, 0);
  cloneOpacity;

download project example

Directional Movement Limiter (Constraints on Position)

Restrains an object’s movement to specific axis limits, simulating boundary constraints.
*add to position property, value reflects positions from [0, 0] (top left)

  minX = 100;
  maxX = 500;
  minY = 200;
  maxY = 800;

  x = clamp(position[0], minX, maxX);
  y = clamp(position[1], minY, maxY);
  [x, y];

download project example

Circular Path with Dynamic Radius (Expanding and Contracting)

Simple endless extenstionto positon, similar to a spirograph

  var basePosition = thisLayer.position; // Get the layer's initial position
  
  // Define the radius with oscillation
  var radius = 100 + Math.sin(time * 2) * 50; 
  var angle = time * 30;
  var x = radius * Math.cos(degreesToRadians(angle));
  var y = radius * Math.sin(degreesToRadians(angle));
  
  // Return the base position plus the animated offset
  [basePosition[0] + x, basePosition[1] + y];
download project example

Endless Position Movement

Simple endless movement extension, similar to "loopOut("continue")".

  value + [0, time*100]

Smooth Expression

Smoothes the keyframes of a property, providing a gradual transition.

  smooth(width, samples = 5)
  

Advanced Repel

The expression allows a layer to keep nudging / pushing assigned layers by a defined value.

  • Name the hero layer "Bully" and this will repel layers with the expression applied to their position.
  • Add slider with "maxdisp" & "mindist" to an adjustment layer named "controls"
  avoidPos = thisComp.layer("Bully").position;
  maxDisplacement = thisComp.layer("Controls").effect("maxdisp")("Slider");
  minDistance = thisComp.layer("Controls").effect("mindist")("Slider");
  finalPos = position.valueAtTime(0);
  oldDirectionVec = normalize([1,1]);
  for( i = 0 ; i <= time; i+= thisComp.frameDuration ){
  try{
  vec = finalPos - avoidPos.valueAtTime( i );
  directionVec = normalize( vec );
  oldDirectionVec = directionVec;
  distance = length( vec );
  displaceAmt = ease( distance , 0 , minDistance , maxDisplacement , 0 );
  displacementVec = displaceAmt * directionVec;
  finalPos += displacementVec
  } catch ( exception ){
  finalPos += oldDirectionVec * displaceAmt;
  }
  }
  finalPos

download project example

Basic Repel

The expression allows a layer push another layer but returns to its original position.

  • Name the hero layer "Bully" and this will repel layers with the expression applied to their position
  avoidPos = thisComp.layer("Bully").position;
  maxDisplacement = 100;  //maximum amount to move the layer
  minDistance = 100;  //minimum distance to begin displacing at
 
  vec = position - avoidPos;
  directionVec = normalize( vec );
  distance = length( vec );
  displaceAmt = ease( distance , 0 , minDistance , maxDisplacement , 0 );
  displacementVec = displaceAmt * directionVec;
  position + displacementVec

download project example

Opacity in relation to camera

Use on 3D layers.

  C = thisComp.activeCamera;
  startFade = thisComp.layer("controller").effect("min distance")("Slider");
  endFade = thisComp.layer("controller").effect("max distance")("Slider");
  maxOpac = thisComp.layer("controller").effect("max opacity")("Slider");

  D = length(toWorld(anchorPoint),C.toWorld([0,0,0]));
  linear(D,startFade,endFade,maxOpac,0);
download project example

Looping Wiggle

Quick way to attach layers and add secondary animation.
*add to the position property.

  freq = 1; // amount of movement
  amp = 110; // how much movement
  loopTime = 3; // amount of time for the loop
  t = time % loopTime;

  wiggle1 = wiggle(freq, amp, 1, 0.5, t);
  wiggle2 = wiggle(freq, amp, 1, 0.5, t - loopTime);
  linear(t, 0,  loopTime, wiggle1, wiggle2)

download project example

Inertial Bounce

Can be added to any property.

  amp = .1;
  freq = 2.0;
  decay = 2.0;
  n = 0;
  time_max = 4;
  if (numKeys > 0){
  n = nearestKey(time).index;
  if (key(n).time > time){
  n--;
  }}
  if (n == 0){ t = 0;
  }else{
  t = time - key(n).time;
  }
  if (n > 0 && t < time_max){
  v = velocityAtTime(key(n).time - thisComp.frameDuration/10);
  value + v*amp*Math.sin(freq*t*2*Math.PI)/Math.exp(decay*t);
  }else{value}

download project example

3D to 2D

An easy way to handle 3D in a 2D space. For example, if you need to parent 2 different spaced layers.
*add to position property of the 3D layer.

  thisComp.layer("3D Layer Name");
  src.toComp([0,0,0]);

Loop Path Keyframe

Seamlessly loop keyframes on a Path Property, use with shape layers or masks.

  if (numKeys >1 && time > key(numKeys).time) {
  t1 = key(1).time;
  t2 = key(numKeys).time;
  span = t2 - t1;
  delta = time - t2;
  t = delta%span;
  valueAtTime(t1 + t)
  } else {
  value
  }

Maintain Stroke Width

keeps the width of the stroke uniform during any scaling.
*add to the stroke proprty in a shape layer

  value / length(toComp([0,0]), toComp([0.7071,0.7071])) || 0.001;
  

download project example

Keyframe Triggered Expression

Expression is triggered by a keyframe.

  • add this expression
  • add your desired expression (to be triggered) inside this.
  • add a marker to THIS layer

  n=0;
  if(marker.numKeys>0) {
  n=marker.nearestKey(time).index;
  if(marker.key(n).time>time) {
  n--;
  } if(n==0) {
  value;
  } else { 
  t=time-marker.key(n).time; //time since marker 
  /// ADD EXPRESSION HERE ///
  }
  } else { 
    value;
  }

download project example

Temporary Parenting

This expression with follow a layer for a from a specified time point for a specified time.

Position example; add this to the "position" of the child layer:

  pickuptime = 1;
  dropofftime = 5.0;
  layertofollow = "specify the layer"
  ticker = Math.min(Math.max(pickuptime, time), dropofftime);
  thisComp.layer("specify the layer").position.valueAtTime(ticker);

Rotation example: add this to the "rotation" of the child layer:

  pickuptime = 1;
  dropofftime = 5.0;
  layertofollow = thisComp.layer("specify the layer")
  ticker = Math.min(Math.max(pickuptime, time), dropofftime);
  thisComp.layer("specify the layer").rotation.valueAtTime(ticker)

download project example

Start Stop Expression

Start and stop an expression at specified timestamps.

  timeToStart = 5;
  timeToStop = 10;
  if ((time > timeToStart) && (time < timeToStop)) {
  /// ADD YOUR EXPRESSION HERE ///
  } else {
  value; }

Delay And Index Layer

Adds a delay to the layer above the previous layer.

  var delay = 5;
  var multiplyDelay = delay * ( index - parent.index )
  parent.fromComp( toComp( anchorPoint, time - framesToTime( multiplyDelay ) ) );

download project example

Automatic Text Box

add this expression to the anchor point of the text layer name "Text Layer 1"

  a=thisLayer.sourceRectAtTime();
  Height=a.height;
  Width=a.width;
  Top=a.top;
  Left=a.left;
  x=Left+Width/2;
  y=Top+Height/2;
  [x,y]

add this expression on the "Size" property of the a rectangular shape layer.

  box=thisComp.layer("Text Layer 1").sourceRectAtTime();
  Width=box.width;
  Height=box.height;
  p=effect("Slider Control")("Slider");
  x=Width+p;
  y=Height+p;
  [x,y]

add this expression on the Anchor Point of "transform" property of the shape layer and add a slider to the shape layer that will control padding.

  box=thisComp.layer("Text Layer 1").sourceRectAtTime();
  Width=box.width;
  Height=box.height;
  Top=box.top;
  Left=box.left;
  p=effect("Slider Control")("Slider");
  x=Width/-2-Left;
  y=Height/-2-Top;
  [x,y]

download project example

Squash and Stretch

  maxDev = 13; // max deviation in pixels
  spd = 30; //speed of oscillation
  decay = 1.0; //how fast it slows down
  t = time - inPoint;
  x = scale[0] + maxDev*Math.sin(spd*t)/Math.exp(decay*t);
  y = scale[0]*scale[1]/x;
  [x,y]

Blink / Strobe

  blinkSpeed=15;
  n= Math.sin(time*blinkSpeed);
  if(n<0) 0 else 100;

Auto Roll

Automatically calculates a roll based on position.

  thisLayer.transform.position[0] * 0.8

  

download project example

Point To A Target

Calculates the angle between 2 layers.

  target = thisComp.layer("Target");
  targetPos = target.toWorld(target.anchorPoint);
  delta = targetPos - thisLayer.position;
  radians = Math.atan2(delta[1], delta[0]);
  radiansToDegrees(radians);

download project example

Number Counter with Seperators

  num = effect("Slider Control")("Slider").value.toFixed(2).toString().replace(".", ",");
  function addCommas(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
  }
  addCommas(num);

Count the number of rotations

Can be adjusted to count any angle.

  count = Math.floor(thisComp.layer("square").transform.rotation / 360); 
  num = count + 100;
  val = ( num % 4);

Blinking Curser, Type Text

Add to source text and add a slider and checkbox.

  cursor = "|";
  blinkTime = 1;
  charMod = 1; 
  num = effect("Slider Control")("Slider");
  toggle = effect("Checkbox Control")("Checkbox");
  if (toggle == 1) {
  t = ((time - inPoint) / blinkTime) % 1;
  if (num.numKeys > 2) {n = 0} else {n = 1}
  ux = Math.abs(num.speedAtTime(time + thisComp.frameDuration*n));
  blink = Math.round(ux + t);
  if (blink == 0) {
  cursor = " ";
  }
  } else {
  cursor = " ";
  }
  if (charMod == 0) {
  textAnim = num * text.sourceText.length / 100;
  } else {
  textAnim = num;
  }
  ext.sourceText.substr(0, textAnim) + cursor

Audio Driving Playhead

Convert audio to keyframes, add expression to time0-remap.

  t = timeToFrames(inPoint); 
  i=0;
  while (timeToFrames (l>=t){

Simple Odometer

Apply to source of text.

  val = effect("Slider Control")("Slider");
  s = "" + Math.floor(val);
  while (s.length <7) s = "0"+s;