Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <link href='//fonts.googleapis.com/css?family=Signika+Negative:300,400,600' rel='stylesheet' type='text/css'>
<div id="header"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/16327/logo-man.svg" width="100" style="vertical-align: middle; margin-right: 16px;" /><h1>Advanced staggers in GSAP</h1></div>
<div id="container"></div>
<div id="instructions">
  <div id="controls">
    <div class="control">
      <div class="control-label">from:</div>
      <div class="control-vertical">
        <label for="center"><input type="radio" id="center" name="from" value="center" checked> <code>"center"</code></label>
        <label for="end"><input type="radio" id="end" name="from" value="end"> <code>"end"</code></label>
        <label for="index"><input type="radio" id="index" name="from" value="11"> <code id="fromIndex">11 (index)</code></label>
      </div>
    </div>
    
    <div class="control">
      <div class="control-label">axis:</div>
      <div class="control-vertical">
        <label for="null"><input type="radio" id="null" name="axis" value="null" checked> <code>null</code> (both)</label>
        <label for="x"><input type="radio" id="x" name="axis" value="x"> <code>"x"</code></label>
        <label for="y"><input type="radio" id="y" name="axis" value="y"> <code>"y"</code></label>
      </div>
    </div>
    
    <div class="control">
      <div class="control-label">ease:</div>
      <div class="control-vertical">
        <label for="linear"><input type="radio" id="linear" name="ease" value="Linear.easeNone" checked> <code>Linear.easeNone</code></label>
        <label for="easeInOut"><input type="radio" id="easeInOut" name="ease" value="Power3.easeInOut"> <code>Power3.easeInOut</code></label>
        <label for="easeOut"><input type="radio" id="easeOut" name="ease" value="Power2.easeIn"> <code>Power2.easeIn</code></label>
      </div>
    </div>
    
  </div>
  <p>Play with the options above to see how it affects the animation and the code below. Click any box to have the stagger emanate outward from that specific index number, using the <code class="featured">from:[index]</code> syntax.</p>
  <div class="code">
    <code>TweenMax.staggerTo(".box", 1, {</code><br>
    <code>&nbsp;&nbsp;scale: 0.1,</code><br>
    <code>&nbsp;&nbsp;y: 40,</code><br>
    <code>&nbsp;&nbsp;ease: Power1.easeInOut,</code><br>
    <code class="featured">&nbsp;&nbsp;stagger: {</code><br>
    <code class="featured">&nbsp;&nbsp;&nbsp;&nbsp;grid: [15,9],</code><br>
    <code class="featured">&nbsp;&nbsp;&nbsp;&nbsp;from: <span id="from">"center"</span>,<br></code>
    <code id="axisCode" class="featured" style="display:none;">&nbsp;&nbsp;&nbsp;&nbsp;axis: <span id="axis">null</span>,<br></code>
    <code id="easeCode" class="featured" style="display:none;">&nbsp;&nbsp;&nbsp;&nbsp;ease: <span id="ease">Linear.easeNone</span>,<br></code>
    <code class="featured">&nbsp;&nbsp;&nbsp;&nbsp;amount: 1.5</code><br>
    <code class="featured">&nbsp;&nbsp;}</code><br>
    <code>});</code>
  </div>
  
  <h2>How does it work?</h2>
  <p>As of <a href="https://greensock.com/2-1">GSAP 2.1.0</a>, all of the stagger methods recognize a new <code class="featured">"stagger"</code> special property which can be an object, a number, or a function as described below:</p>
    
   
  <h3>Object</h3>
    <p>An object makes configuration simple. It may contain any of the following properties:</p> 
<ul>
  <li><strong>amount</strong> [number]: the total amount of time (in seconds) that gets split up among all the staggers. So if <code>amount</code> is <code>1</code> and there are 100 elements that stagger linearly, there would be 0.01 seconds between each tween's start time. If you prefer to specify a certain amount of time between each tween, use the <code>each</code> property <i>instead</i>. A negative <code>amount</code> will invert the timing effect which can be very handy. So <code>{amount:-1, from:"center"}</code> would cause staggers to go from the outer edges in toward the center.</li>
  <li><strong>each</strong> [number]: the amount of time (in seconds) between each animation's start time. So if <code>each</code> is <code>1</code> (regardless of how many elements there are), there would be 1 second between each tween's start time. If you prefer to specify a <strong>total</strong> amount of time to split up among the staggers, use the <code>amount</code> property <i>instead</i>. A negative <code>each</code> will invert the timing effect which can be very handy. So <code>{each:-1, from:"center"}</code> would cause staggers to go from the outer edges in toward the center. <i>(Added in 2.1.1)</i></li>
  <li><strong>from</strong> [string | integer]: the position in the array from which the stagger will emanate. To begin with a particular element, for example, use the number representing that element's index in the target array. So <code>from:4</code> begins staggering at the 5th element in the array (because arrays use zero-based indexes). The animation for each element will begin based on the element's proximity to the "from" value in the array (the closer it is, the sooner it'll begin). You can also use the following string values: <code>"start"</code>, <code>"center"</code>, or <code>"end"</code>. Default: 0.</li>
  <li><strong>grid</strong> [array | "auto"]: if the elements are being displayed in a grid visually, indicate how many columns and rows there are (like <code>grid:[15,9]</code>) so that GSAP can calculate proximities accordingly. Or use <code>grid:"auto"</code> to have GSAP automatically calculate the rows and columns using <code>element.getBoundingClientRect()</code> (great for responsive layouts). Grids are assumed to flow from top left to bottom right layout-wise (like text that wraps at the right edge). Or if your elements aren't arranged in a uniform grid, check out the <a href="https://codepen.io/GreenSock/pen/gyWrPO?editors=0010" target="_top">distributeByPosition() helper function</a> we created.</li>
  <li><strong>axis</strong> [string]: if you define a <code>grid</code>, staggers are based on each element's total distance to the "from" value on both the x and y axis, but you can focus on just one axis if you prefer (<code>"x"</code> or <code>"y"</code>). Use the demo above to see the effect (it makes more sense when you see it visually).</li>
  <li><strong>ease</strong> [Ease]: the ease that distributes the start times of the animation. So <code>Power2.easeOut</code> would start out with bigger gaps and then get more tightly clustered toward the end. Default: <code>Linear.easeNone</code>.</li>
  </ul>
  
  <h3>Number</h3>
  <p>A value like <code>stagger:0.1</code> would cause there to be 0.1 second between the start times of each tween. A negative value would do the same but backwards so that the last element begins first.</p>
  
  <h3>Function</h3>
  <p>The function is called once for each target/element in the array and should return the total delay from the starting position (not the amount of delay from the previous tween's start time). The function receives the following parameters:</p>
  <ol>
    <li><strong>index</strong> [integer] - the index value from the list</li>
    <li><strong>target</strong> [object] - the target in the list at that index value</li>
    <li><strong>list</strong> [array | NodeList] - the targets array (or NodeList)</li>
  </ol>
  <p>For example, to stagger from the outer edges to the center over the course of 2 seconds:</p>
  <div class="code">
    <code>TweenMax.staggerTo(".box", 1, {</code><br>
    <code>&nbsp;&nbsp;scale: 0.1,</code><br>
    <code class="featured">&nbsp;&nbsp;stagger: function(index, target, list) {</code><br>
    <code class="featured">&nbsp;&nbsp;&nbsp;&nbsp;var maxStagger = 2,<br></code>
    <code class="featured">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;middleIndex = ((list.length - 1) / 2);,<br></code>
    <code class="featured">&nbsp;&nbsp;&nbsp;&nbsp;return (1 - (Math.abs(index - middleIndex) / middleIndex)) * maxStagger;,<br></code>
    <code class="featured">&nbsp;&nbsp;}</code><br>
    <code>});</code>
  </div>
  
  <h2>Video Explanation</h2>
  <span class="fr-video"><iframe width="560" height="315" src="https://www.youtube.com/embed/o0VAGbDymxA" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></span>
  
  
  <h2>FAQ</h2>
  <p>
    <span class="question">What about the stagger parameter?</span>
    You can still use the stagger parameter, and it works the way it always has. You can even pass an advanced stagger object (or function) as the parameter. We simply added the ability to define it as a special property in the vars object (which overrules the parameter) for readability.  
  </p>
  
  <p>
    <span class="question">Is this only useful for grids?</span>
    Absolutely not! You can get some slick effects by leveraging <code>ease</code> to add more organic spacing, or use the <code>from</code> property to have things emanate outward from a specific element index or the <code>"center"</code>. Even just using <code>amount</code> can be useful because it gives you tight control over when all the staggering will finish regardless of how many elements are in the target array. Normal staggering didn't offer that. 
  </p>
  
  <p>
    <span class="question">Does grid:"auto" work for responsive layouts after resize?</span>
    No, stagger values get calculated immediately when the stagger method is called, so if the layout changes after that, you'd need to handle that logic on your own. For example, you could use a TimelineLite/Max stagger method so that everything is in one instance, then have a resize listener that rewinds the timeline to its starting values, clears it, and then redoes the stagger. <code>timeline.time(0).clear(); timeline.staggerTo(...);</code> Ask in the <a href="https://greensock.com/forums/">forums</a> if you need any help with that. 
  </p>
  
  <p>
    <span class="question">What if my elements aren't in a uniform grid (gaps, different sizes, etc.) - can I stagger them based on position?</span>
    Sure, that's the perfect time to use a function-based value. In fact, we've created a <a href="https://codepen.io/GreenSock/pen/gyWrPO?editors=0010" target="_top">distributeByPosition() helper function</a> for this very case that should make it crazy simple for you!.
  </p>
  
  <p>
    <span class="question">It's not working for me! Why not?</span>
    Make sure you're loading <a href="https://greensock.com/?download=GSAP-JS">GSAP 2.1.0</a> or higher (you might need to empty your cache). And keep in mind that it only works in the <code>staggerTo()</code>, <code>staggerFrom()</code>, and <code>staggerFromTo()</code> methods of TweenMax / TimelineLite / TimelineMax. It can't work in regular <code>to() / from() / fromTo()</code> methods because a single tween only has one startTime(). The <code>staggerTo() / staggerFrom() / staggerFromTo()</code> methods create multiple tween instances which is why they can do staggering.
  </p>
</div>

            
          
!
            
              html, body {
  width: 0;         /* for fixing iOS iframe issues */
  min-width: 100%;  /* for fixing iOS iframe issues */
  overflow-x: hidden;
  position: relative;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  background-color: #222;
  text-align: center;
  color: #bbb;
  font-family: "Signika Negative", sans-serif;
  font-weight: 300;
  font-size: 18px;
  padding: 10px 0;
}
h1 {
  margin: 0;
  font-size: 50px;
  text-align: left;
}
h2 {
  font-size: 38px;
  margin-bottom: 0;
}
h1, h2, h3 {
  color: white;
  font-weight: 400;
}
h3 {
  margin-bottom: -12px;
}
#header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
a {
  color: #88ce02;
  text-decoration: none;
  font-weight: 400;
}
a:hover {
  text-decoration: underline;
}
#container {
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: visible;
}
.box {
  background-color: #88ce02;
  position: relative;
}
.box:before {
  padding-top:100%;
  content:"";
  display:block;
}
#instructions {
  margin-top: 35px;
  padding:0 16px 16px 16px;
  text-align: left;
  max-width: 1000px;
  display: inline-block;
}

.code {
  background-color: #111;
  padding: 12px;
  border-radius: 10px;
}
.featured {
  color: white;
}
strong {
  color: white;
  font-weight: 400;
  font-size: 20px;
}
.question {
  color: white;
  font-size: 21px;
  font-weight: 400;
  display: block;
}
#controls {
  text-align: center;
  display:flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}
.control {
  display: flex;
  align-items: flex-start;
  font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace;
  color: white;
  margin-bottom: 10px;
}
.control-label {
  margin-top: 10px;
}
.control-vertical {
  display: flex;
  flex-direction: column;
  align-content: flex-start;
  text-align: left;
  justify-content: flex-start;
  padding: 6px 8px;
  border-radius: 9px;
  background-color: #111;
  margin-right: 18px;
  color: #bbb;
}

.fr-video {
  display: block;
  position: relative;
  width: 100%;
  height: 0;
  float: left;
  padding-bottom: 56.25%;
  margin: 12px 0 35px 0;
}

.fr-video iframe {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  border: 2px solid #444;
}

#instructions li {
  margin-bottom: 10px;
}

@media only screen and (max-width: 640px) {
  h1 {
    font-size: 30px;
    line-height: 30px;
  }
  #controls {
    align-items: flex-start;
    justify-content: flex-start;
  }
}
            
          
!
            
              //GSAP 2.1.0 introduces advanced stagger values
var grid = [15,9], //[colums, rows]
    tl = new TimelineMax({repeat:-1, repeatDelay:0.5});

function animateBoxes(from, axis, ease) {
  //one stagger call does all the animation:
  tl.staggerTo(".box", 1, {
      scale:0.1, 
      y:60,
      yoyo:true, 
      repeat:1, 
      ease:Power1.easeInOut,
      stagger: {
        amount:1.5, 
        grid:grid, 
        axis:axis, 
        ease:ease,
        from:from
      }
    }
  );
}




//builds a grid of <div class="box"> elements, dropped into #container (unrelated to animation code)
buildGrid({grid:grid, className:"box", width:1000, gutter:15, parent:"#container", onCellClick:onCellClick});

animateBoxes("center");




//---- the rest of the code below just handles all the interactivity ----

var options = document.querySelectorAll('input[name="from"], input[name="axis"], input[name="ease"]'),
    _select = function(selector) {
      return document.querySelector(selector);
    },
    axisCodeEl = _select("#axisCode"),
    axisEl = _select("#axis"),
    easeCodeEl = _select("#easeCode"),
    easeEl = _select("#ease"),
    fromEl = _select("#from"),
    fromIndexEl = _select("#fromIndex"),
    indexEl = _select("#index"),
    selections = {from:"center", axis:null, ease:Linear.easeNone},
    i;

//add change listeners
for (i = 0; i < options.length; i++) {
  options[i].addEventListener("change", onOptionChange);
}

function onOptionChange(e) {
  var group = e.target.getAttribute("name"),
      value = e.target.getAttribute("value");
  if (group === "from") {
    updateFrom(value);
  } else if (group === "axis") {
    selections.axis = (value === "null") ? null : value;
    axisCode.style.display = (value === "null") ? "none" : "inline";
    axisEl.textContent = '"' + value + '"';
  } else if (group === "ease") {
    easeEl.textContent = value;
    easeCodeEl.style.display = (value === "Linear.easeNone") ? "none" : "inline";
    value = value.split(".");
    selections.ease = window[value[0]][value[1]];
  }
  updateAnimation();
}

function updateFrom(value) {
  var current = selections.from,
      parsedVal = value,
      newIsNumber = !isNaN(value),
      oldIsNumber = !isNaN(current);
  if (newIsNumber) {
    parsedVal = parseInt(value, 10);
  } else if (value === "end") {
    parsedVal = grid[0] * grid[1] - 1;
    newIsNumber = true;
  }
  if (current !== parsedVal) {
    selections.from = parsedVal;
    fromEl.textContent = (value === "end") ? '"end"' : newIsNumber ? value : '"' + value + '"';
    if (newIsNumber && !oldIsNumber) {
      TweenMax.to(".box", 0.3, {backgroundColor:"#595959"});
    } else if (!newIsNumber && oldIsNumber) {
      TweenMax.to(".box", 0.3, {backgroundColor:"#88ce02"});
    }
    if (newIsNumber) {
      if (value !== "end") {
        indexEl.checked = true;
        indexEl.setAttribute("value", parsedVal);
        fromIndexEl.textContent = parsedVal + " (index)";
      }
      TweenMax.fromTo("[data-index='" + parsedVal + "']", 0.4, {rotation:0}, {rotation:360, backgroundColor:"#88ce02", ease:Power1.easeInOut});
      if (oldIsNumber) {
        TweenMax.to("[data-index='" + current + "']", 0.3, {backgroundColor:"#595959"});
      }
    }
  }
}

function onCellClick(e) {
  updateFrom(e.target.index);
  updateAnimation();
}

function updateAnimation() {
  tl.seek(0).clear();
  animateBoxes(selections.from, selections.axis, selections.ease);
}

//helper function to build a grid of <div> elements
function buildGrid(vars) {
	vars = vars || {};
	var container = document.createElement("div"),
		rows = vars.grid[1] || 5,
		cols = vars.grid[0] || 5,
		width = vars.width || 100,
		gutter = vars.gutter || 1,
    className = vars.className || "",
		w = (width - cols * gutter) / cols,
		parent = (typeof(vars.parent) === "string") ? document.querySelector(vars.parent) : vars.parent ? vars.parent : document.body,
		css = "display: inline-block; margin: 0 " + (gutter / width * 100) + "% " + (gutter / width * 100) + "% 0; width: " + (w / width * 100) + "%;",
		l = rows * cols,
		i, box;
	for (i = 0; i < l; i++) {
		box = document.createElement("div");
		box.style.cssText = css;
    box.setAttribute("class", className);
    box.index = i;
    box.setAttribute("data-index", i);
    if (vars.onCellClick) {
      box.addEventListener("click", vars.onCellClick);
    }
		container.appendChild(box);
	}
	container.style.cssText = "width:" + width + "px; line-height: 0; padding:" + gutter + "px 0 0 " + gutter + "px; display:inline-block;";
	parent.appendChild(container);
	return container;
}

//this just helps avoid the pixel-snapping that some browsers do.
TweenMax.set(".box", {rotation:0.5, force3D:true});
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console