Joseph Carolina Joseph Carolina -3 years ago 94
jQuery Question

jQuery Animation in a forEach loop

I am trying to attach jQuery

with an
in a
loop the following way:

items.forEach(function (item) {

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=""></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