Joseph Carolina Joseph Carolina - 1 year ago 66
jQuery Question

jQuery Animation in a forEach loop

I am trying to attach jQuery

.fadeIn("slow");
with an
append();
in a
forEach();
loop the following way:

items.forEach(function (item) {
showData.append('<div>Test</div>').fadeIn('slow');
});


However, as soon as the loop is trigger the amount of div's being added are still not being added with the fade effect. Any ideas of how I can get the fade effect work either via jQuery or CSS whatever is the best solution.

Answer Source

You're animating the showData element, whatever that is, and it's probably already visible.
What you wanted was probably to animate the inserted DIV instead

To make the elements appear one after the other, you could use a delay that increases with each iteration

var items  = [1, 2, 3, 4, 5, 6],
  showData = $('#test');

items.forEach(function(item, index) {
  $('<div />', {
    text : 'Test',
    css  : {display: 'none'}
  }).delay(index * 600).fadeIn('slow').appendTo(showData);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

Of course, the element must be hidden before it can be faded in

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download