Search code examples
jqueryfade

replacing old content with in along with fadeOut/In with jQuery


I have a web-based application with a div, typically a left nav. Normally with a width declared, but potentially not (i.e. just filling a parent container)

Then I'll use jquery as follows:

$('#thatdiv').load('http://example.com/ajax/url-etc');

and it works fine. However, I would like to do in pretty much this order:

  1. fade out the old content
  2. fade in the new content
  3. simlutaneously, transition the height from the height of the old to the height of the new content, either pushing down or collapsing up.

Here is my very first jsFiddle: http://jsfiddle.net/sfullman/4zhdov58/.

Although I'm fairly familiar with ajax and the jquery.post method, I would appreciate feedback on the most robust method of doing this. Again, normally the width will be fixed, so the transition will be in the height

Any links or examples would be greatly appreciated as I add this skill to my repertoire


Solution

  • You should use $.ajax function, which provides some options to get the behavior you want:

    $.ajax({
      url: "http://example.com/ajax/url-etc",
      beforeSend: function() {
         $('#thatdiv').fadeOut('slow');
      }
      success: function(response) {
         $('#thatdiv').append(response);
      }
    }).always(function() {
         $('#thatdiv').fadeIn('slow');      
    });
    

    Hope it helps.

    Regards.