简体   繁体   中英

How can we append a list of elements one by one with fade-in effect inside jQuery $.each method

I Have a json response getting through jQuery Ajax ( $.ajax ) on .done() callback I am manipulating response to an html output

.done(function(response) {
     $.each(response, function(i, video) {
        html = '<div class="col-lg-6">'+response.img+'</div>";
        $(html).appendTo('#myImages');
    })    
})

So, the above code works perfectly, but the thing I want to acheive is, I want to appear each divs with image[append var=html to #myImages] one by one with a slight fadeIn effect, so How can I add this. I was checking with setTimeout function, but that does't work as I want.

To make it fading-in you may try following:

$(html).hide().appendTo('#myImages').fadeIn(1000);

Next, if you want to build a sequence, there are some ways to do it, here's simplest async/await try:

async function render(item, delay) {
  html = '<div class="col-lg-6">' + item.img + '</div>";
  $(html).hide().appendTo('#myImages').fadeIn(delay);

  return new Promise(function(resolve){
    setTimeout(function() {
      resolve();
    }, delay);
  })
}

.done(function(response) {
  for(var i = 0; i < response.lenght; i++) {
    try {
      await render(response[i], 1000);
    }
    catch(err) {
      console.log(err);
    }
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM