How to fade out div slowly, update content, and then fade in div slowly, using jQuery?

Alex Reynolds picture Alex Reynolds · May 4, 2011 · Viewed 34.9k times · Source

I have a div I want to fade out, update its content, and then fade back in. So far I have tried:

$('#myDivID').fadeOut('slow', function() {
    $('#myDivID').replaceWith("<div id='myDivID'>" + content + "</div>");
    $('#myDivID').fadeIn('slow');
});

What happens is that the fade out completes and calls the anonymous callback. So far, so good.

The div's content is replaced correctly, but the fadeIn() effect is immediate — no smooth transition, just a quick, snappy jump to the updated div.

Is there a better way to accomplish this? Thanks for your advice.

Answer

Edgar Villegas Alvarado picture Edgar Villegas Alvarado · May 4, 2011

You should do it this way (this works, is tested code):

$('#myDivID').fadeOut('slow', function() {
    $('#myDivID').html(content);
    $('#myDivID').fadeIn('slow');
});

Your code wasn't working because the new created div is instantly visible. Another solution is to add a display:none like the following:

   $('#myDivID').fadeOut('slow', function() {
      $('#myDivID').replaceWith("<div id='myDivID' style='display:none'>" + content + "</div>");
      $('#myDivID').fadeIn('slow');
  });

Hope this helps Cheers