$ .each animation works separately

I try to run each animation function one by one, and not immediately.

This is what I have so far:

   $(document).ready(function(){ 
        var bars = $('.bar');
        bars.each(function(){
            var widthpercent = $(this).attr("data-percent");
            $(this).fadeIn();
            $(this).animate({width:widthpercent},500);
        });
    });

I tried to use .delay()and setTimeout()in various combinations to no avail.

Can someone point me in the right direction? Thank!

+3
source share
3 answers

, animate complete. complete , . : , , , . complete, , , .

, .

().

var $divs = $('div');

function animate(element) {
  $(element).animate({height: '30px'}, {
    complete: function() {
      if (current < $divs.length-1) {
        ++current;
        animate($divs[current]);
      }
    }
  });
}

var current = 0;
animate($divs[current]);

, fadeIn. fadeIn , :

().

var $divs = $('div');

function animate(element) {
  $(element).fadeIn(function() { //now the animation is a callback to the fadeIn
    $(element).animate({height: '70px'}, {
      complete: function() {
        if (current < $divs.length-1) {
          ++current;
          animate($divs[current]);
        }
      }
    });
  });
}

var current = 0;
animate($divs[current]);

: ().

$(document).ready(function(){ 

var $divs = $('.bar');

function animate(element) {
  $(element).fadeIn(function() { //you could unwrap this depending on what you're looking for
    var widthpercent = $(element).attr("data-percent");
    $(element).animate({
      width:widthpercent,
      duration: '500ms'
    }, {
      complete: function() {
        if (current < $divs.length-1) {
          ++current;
          animate($divs[current]);
        }
      }
    });
  }); //end fadeIn callback
}

var current = 0;
animate($divs[current]);

});
+5

:

var animate = function (el) {
    return function () {
        var widthpercent = el.data('percent');
        el.fadeIn();
        el.animate({
            width: widthpercent
        }, 500);
    }
}
var bars = $('.bar');
bars.each(function (index) {
    var $this = $(this);
    setTimeout(animate($this), index * 500);
});

Fiddle

+3
$(document).ready(function(){ 
    var bars = $('.bar');
    bars.each(function(i){
        var widthpercent = $(this).attr("data-percent");
        $(this).delay(i*800).animate({width:widthpercent,opacity:1,},500);
    });
});

800 * i .

. JSFiddle.

+1

All Articles