Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery replacewith fade/animate

Tags:

jquery

$('#foo').fadeOut("slow", function(){
    var div = $("<div id='foo'>test2</div>").hide();
    $(this).replaceWith(div);
    $('#foo').fadeIn("slow");
});

jsfiddle - http://jsfiddle.net/9Dubr/1/

Updated to fade in correctly


$('#foo').fadeOut("slow", function(){
  $('#foo').html(data);
  $('#foo').fadeIn("slow");
}

I successfully use this pattern to GET+fadeOut+fadeIn (with jQuery 1.11.0):

$.get(url).done(function(data) {
    $target.fadeOut(function() {
        $target.replaceWith(function() {
            return $(data).hide().fadeIn();
        });
    });
});

where $target is the element to replace.


Richard Daltons answer is correct and is useful.

In case anyone else is looking to solve a very similar situation, but with a lot more content being updated, the following worked for me. My example includes 'response', which is an Ajax returned heap of HTML.

$('.foo').fadeOut("slow", function() {
  var div = jQuery('<div style="display:none;" class="foo">'+response+'</div>');
  $('.foo').replaceWith(div);
  $('.foo').fadeIn("slow");
});

The reason with the .hide() needs to be changed is that it applies it to all elements within the response. There may be more elegant solutions than this, but it works.


This version will 'live' on ;)

jsfiddle effort