4lackof
4lackof

Reputation: 1390

JS - load animation for each element passed from AJAX call

I have a webpage which does an AJAX call when someone searches for something. I want it so that when the results load in each result does a specific "loading animation" (like, each search result fades in separately - not the entire group of results fading in together).

How I currently have the JS is that all the objects get put in at the same time, but that only allows for me to style all of them at the same time.

Here's my code:

JS:

$.ajax({
  type: 'GET',
  url: '/Search',
  data: {
    'search_value': str
  },
  dataType: 'text',
})
.done(function(json) {
  var Search = JSON.parse(json), searchHTML = '', x;
  for (x in Search) {
    $('<span id="item'+x+"' class="search-item" style="display: none;">'+  Search[x] + '</span>').appendTo('#main');
    //this is to set the fade it
    //(the .css is there so it isn't accidentally forgotten about in the css)
    $('.search-item').css('opacity', '0');
    $('.search-item').fadeTo(500, 1);
  }

});

HTML

<div id="main">

</div>

I am trying to make it so that instead of all the html getting set at the end, it adds on to the last one, or something like that AND ALSO so that each one has an animation setting fire for it when it gets loaded into the html

Thank you

UPDATE

The code has been updated with code from an answer below. still need the code to fire a new "load in animation" for each search response.

Upvotes: 1

Views: 377

Answers (1)

cнŝdk
cнŝdk

Reputation: 32145

In your case you can use jquery .show() function with appendChild() function, here's how will be your code:

$.ajax({
  type: 'GET',
  url: '/Search',
  data: {
    'search_value': str
  },
  dataType: 'text',
})
.done(function(json) {
  var Search = JSON.parse(json), searchHTML = '', x;
  for (x in Search) {
    $('<span id="item'+x+"' class="search-item" style="display: none;">'+  Search[x] + '</span>').appendTo('#main').show('slow');
  }
});

Upvotes: 1

Related Questions