15

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.

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345

6 Answers6

25

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

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
5

use SetTimeOut

setTimeout(function() { $('#myDivID').fadeIn('slow'); }, 5000);

this works

jsFiddle http://jsfiddle.net/3XYE6/1/

$('#doit').click(function(){
    $('#myDivID').fadeOut('slow', function() {
        $('#myDivID').html('New content in MyDiv ('+Math.random()+')')
        setTimeout(function() { $('#myDivID').fadeIn('slow'); }, 5000);
    });    
})
kobe
  • 15,671
  • 15
  • 64
  • 91
2

this should do it!

http://jsfiddle.net/3XYE6/

netbrain
  • 9,194
  • 6
  • 42
  • 68
1

Something like this would work:

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

Test here: http://jsfiddle.net/tomgrohl/PgcTZ/

I've put the hide before the delay to make the animation work.

Tomgrohl
  • 1,767
  • 10
  • 16
1

When you use replaceWith the content will be visible that is why there is no smooth transition.

First hiding the div and then calling fadeIn will give smooth transition.

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

Try this.

http://jsfiddle.net/X3cnT/

$('#myDivID').fadeOut('slow', function() {
        $('#myDivID').html("all this text");
        $('#myDivID').fadeIn('slow');
});
calumbrodie
  • 4,722
  • 5
  • 35
  • 63