Antonio Papalillo
Antonio Papalillo

Reputation: 1342

javascript: jQuery replaceWith() not respecting delay()

this is my first post here. I have searched a lot but I haven't found anything regarding this.

I have this little script not working as expected (it runs without errors):

(function ($) {
    $("div#replace").click(function () {
        $(this).fadeOut("200").delay("200").replaceWith("<div id='replace'>new content</div>").delay("200").fadeIn("200");
    });
})(jQuery);

I was expecting this from div#replace:

Fade out -> Change content -> Fade in

Instead, I got this behavior:

Change content -> Fade out -> Fade in


[EDIT] Thank you guys, I have a solution. I'm posting it here:

I'm using Spokey's approach and I have switched from replaceWith() to html(), which got the fadeIn animation working correctly.

$("div#replace").click(function() {
    $(this).fadeOut("200", function() {
        $(this).html("new content").fadeIn("200");
    });
});

Thank you! And sorry for my bad english :)

Upvotes: 2

Views: 642

Answers (2)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262979

replaceWith() is not tied to the animation queue, so delay() will not affect its behavior.

You can, however, use queue() and dequeue() to tie arbitrary code to the animation queue:

$(this).fadeOut("200").delay("200").queue(function(next) {
    $(this).replaceWith("<div id='replace'>new content</div>");
    next();
}).delay("200").fadeIn("200");

Note that I use the next method provided by queue() to signal that the next animation step can start, instead of chaining into dequeue() as in my original answer.

That's because dequeue() relies on the matched elements, and since replaceWith() removes these elements from the DOM I wasn't 100% positive dequeue() would work on them.

Upvotes: 1

Spokey
Spokey

Reputation: 10994

You can use the fadeOut callback (when fade finished) to replace the div and then show it again.

(function ($) {
    $("div#replace").click(function () {
        $(this).fadeOut("200", function(){
            $(this).replaceWith("<div id='replace'>new content</div>").fadeIn("200");
        });
    });
})(jQuery);

Upvotes: 0

Related Questions