4lackof 4lackof - 4 months ago 9
Ajax Question

CSS/AJAX - Activate style on AJAX call

I have a search feature which uses AJAX to populate the search result field. I want to style each search result as it gets added in with some effect (like a "loading-in-animation"). I currently have this 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');
}
});


this works, however
.show()
I have found is a bit performance heavy and so as such wanted to lessen how much performance used to animate the loading of each search results.

I tried setting up this:

$.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 off" style="display: none;">'+ Search[x] + '</span>').appendTo('#main').removeClass('off');
}
});


then my CSS for this is:

.search-item{
max-height: 256px;
overflow: hidden;
transition: 3s;
}
.search-item.off{
max-height: 0px;
}


by doing this it removes the off immediately, which then uses the
transition
CSS attribute to make it grow over 3 seconds (just a testing time - it will probably be something like
0.5s
or something).

The only problem is that it is just removing the class but no transition effect happens (if I remove the
removeClass()
code and then remove the class using firebug or another dev tool. it works fine).

Does anyone know how to fix this and get it so that the
transition
attrib applies and the results don't instantly get displayed?


Thank you.

Answer

It removes the class before the element is even added to the DOM, use a timeout of some sort to defer the removing of the class until after the element is inserted.
I'd prefer the native setTimeout, but jQuery has queue() and delay() that can be used to create the same effect.

$.ajax({
  type  : 'GET',
  url   : '/Search',
  data  : {
    'search_value': str
  },
  dataType : 'json'
}).done(function(json) {

    $.each(json, function(key, value) {
        var span = $('<span />', {
           id      : 'item' + key,
           'class' : 'search-item off',
           style   : 'display : none',
           text    : value
        }).appendTo('#main');

        setTimeout(function() {
            span.removeClass('off')
        });
    });

});
Comments