Stagger css animation with jquery

I wonder if there are any ways to do it. For example I have an animation like this demo on Codepen. After 500ms, the next cube will be animating. How can I make the next cube animate after 1/2 of the first animation time. I know how to make it with .animate(), but this time it is .css() and I can't find a way to do it. I appreciate it!

$(function() {
  $('button.action').on('click', function() {
    $('.wrap .item').each(function(i) {
      var $item = $(this);
      setTimeout(function() {
        $item.css({
          'opacity': 1,
          'transform': 'translateX(0)'
        });
      }, 500*i);
    });
  });
});

The next animation will start at 1/2 of the first animation time. Not at the end of the first one.

Answers 1

  • As I got it, you want to start animation sequentially item by item, by make it shorter for each next item so they all will got the destination simultaneously. Take a look at this example. Notice: each animation is not 1/2 of the previous one, but 1/n shorter, where n is number of items, i.e. for seven items it would be: 1000ms -> 857 -> 714 -> 571, otherwise the latest would be too short in my opinion.

    $(function() {
      $('button.action').on('click', function() {
        setTimeout(function() {
          var items = $('.wrap .item');
          var total = items.length;
          items.each(function(i) {
            var initial = 1000;
            var delay = initial - initial / (total + 1) * (total - i);
            var speed = initial - initial / (total + 1) * i;
            var item = $(this);
            item.css({
              'transition-delay': delay + 'ms',
              'transition-duration': speed + 'ms',
              'opacity': 1,
              'transform': 'translateX(0)'
            });
          });
        });
      });
    });
    .item {
      display: block;
      margin: 5px;
      width: 40px;
      height: 40px;
      background-color: #cd3455;
      transform: translateX(100px);
      opacity: 0.5;
      transition: all .5s cubic-bezier(.49,-0.57,1,.99)
    }
    .action {
      position: absolute;
      top: 5%;
      right: 5%;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="wrap">
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
    </div>
    
    <button class="action">Action!</button>


Related Articles