Alon
Alon

Reputation: 7758

How to create an ajax request and a background animation simultaneously

I have this piece of code:

    $('#contentSites').fadeOut(200, function() {
        // Animation complete
            $.get("my_account_content.php?q=" + content, function(data){
                $("div#contentSites").html(data);
                $('#contentSites').fadeIn(200);
});

I have 2 buttons that activates the ajax request and changes the whole content of #contentSites - right now it does 3 things one by one (only executes the next one until the previous one is finished). It does this: 1. fade out the current content 2. get the new content 3. fade in the new content.

Since this is not highly efficient (since that I need to wait until the fadeout happens before the ajax request).

I wanted to ask how to fire simultaneously the fadeout and the ajax request and only when the ajax request has finished to do the fade in.

Upvotes: 0

Views: 232

Answers (2)

aziz punjani
aziz punjani

Reputation: 25776

You would simply remove the callback on fadeOut

$('#contentSites').fadeOut(200);
$.get("my_account_content.php?q=" + content, function(data){
    $("div#contentSites").html(data);
    $('#contentSites').fadeIn(200);
});

Another way to do it using jQuery defferds would be

$.when( $('#contentSites').fadeOut(200), get_content() ).then(function(){ 
    $('#contentSites').fadeIn(200);
}); 

function get_content(){
   return $.get("my_account_content.php?q=" + content, function(data){
             $("div#contentSites").html(data);
          });
}

This will ensure that fadeIn is only run after both the ajax request and the fadeOut have finished, while running both simultaneously.

Upvotes: 3

Darek Rossman
Darek Rossman

Reputation: 1323

Perhaps this:

$('#contentSites').fadeOut(200);

$.get("my_account_content.php?q=" + content, function(data){
    $("div#contentSites").html(data);
    $('#contentSites').fadeIn(200);
});

Upvotes: 1

Related Questions