Jcfg.J
Jcfg.J

Reputation: 101

Sequencing Animations JQuery/Velocityjs

Essentially, I have multiple divs with the same class name (so like:

<div class = "tile"></div>
<div class = "tile"></div>
<div class = "tile"></div>
<div class = "tile"></div>
...

And I want to animate them in a way that the first div (for example) changes opacity to 0. However, if I just do

$('.tile').animate({opacity: 0});

or

$('.tile').velocity({opacity: 0});

They all change opacity to 0 at the same time. Is there a way to animate single tiles or queue their animations so the first changes, then the second, then the third, etc.?

Upvotes: 2

Views: 74

Answers (2)

Jared Farrish
Jared Farrish

Reputation: 49188

In case you were wondering about an only-jQuery method:

$('.tile').each(function(){
    var $this = $(this),
        $next = $this.prev();
    
    $this.queue(function(){
        $this.fadeOut(1500, function(){
            $this.next().dequeue();
        });
    });
}).first().dequeue();
.tile {
  width: 100px;
  height: 100px;
  background: yellow;
  border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>

Upvotes: 1

cypark
cypark

Reputation: 955

You can achieve it by recursively applying the animation to the next DOM as below:

HTML

<div class = "tile"></div>
<div class = "tile"></div>
<div class = "tile"></div>
<div class = "tile"></div>
<style>
  .tile {
    width: 100px;
    height: 100px;
    background: yellow;
    border: 1px solid blue;
  }
</style>

JS

var counter = 0;
function makeTransparent($target) {
  $target.eq(counter).animate({opacity: 0}, function(){
    counter++;
    if (counter < $target.length) {
      makeTransparent($target);
    }
  });
}

makeTransparent($('.tile'));

Here is the live example: https://jsfiddle.net/uzf67L8c/

Upvotes: 1

Related Questions