Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 416
Alex Reynolds Avatar asked May 04 '11 07:05

Alex Reynolds


People also ask

How do you fadeOut an element in jQuery?

The jQuery fadeOut() method is used to fade out a visible element. Syntax: $(selector). fadeOut(speed,callback);

What is fadeIn and fadeOut in jQuery?

You can use the jQuery fadeIn() and fadeOut() methods to display or hide the HTML elements by gradually increasing or decreasing their opacity.


2 Answers

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

like image 192
Edgar Villegas Alvarado Avatar answered Sep 28 '22 09:09

Edgar Villegas Alvarado


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);
    });    
})
like image 36
kobe Avatar answered Sep 28 '22 09:09

kobe