Remove, Append, and Resize Using jQuery I'm trying to essentially replace an element and make it transition smoothly to the new size... I started off trying to work with the appended element itself, but the padding and margins made that difficult, so I switched to using a container.

var template = "&lt;p&gt;I've replaced the button&lt;br&gt;and in a very smooth&lt;br&gt;fashion!&lt;/p&gt;";

var doAnimation = function(e) {
    var parent = $(this).parent();
    var oldHeight = parent.height();

    $(this).fadeOut(400, function() {
        this.remove();

        var paragraph = $(template).appendTo(parent);
        var newHeight = parent.height();

        paragraph.hide().fadeIn();
        parent.height(oldHeight).animate({height: newHeight});
    });
}

$(document).on('click', 'button', doAnimation);


Here is the demo on jsFiddle: first attempt, second attempt

Is there a better way to go about doing this and how would I extract it to something that's reusable?

Edits: 

3rd attempt - simply extracted the template to the HTML...

4th attempt - added some data attributes and string replacements.
If i'm understanding your question correctly what you have is pretty much there already. The only change I can suggest is to let your HTML establish the relationship between your trigger button and the template containing your new HTML like so:

http://jsfiddle.net/vax6hp28/5/

HTML

&lt;div class="container"&gt;
    &lt;button data-target="#template-addText"&gt;Click Me&lt;/button&gt;
&lt;/div&gt;

&lt;script id="template-addText" type="text/template"&gt;
    &lt;p&gt;I've replaced the button and in a very smooth fashion!&lt;/p&gt;
    &lt;p&gt;Holla!&lt;/p&gt;
&lt;/script&gt;


Javascript

var appendResize = function(e) {
    var parent = $(this).parent();
    var oldHeight = parent.height();
    var templateRef = $($(this).data('target'));

    $(this).fadeOut(400, function() {
        this.remove();

        var template = templateRef.html();
        var paragraph = $(template).appendTo(parent);
        var newHeight = parent.height();

        paragraph.fadeIn(2000);
        parent.height(oldHeight).animate({height: newHeight});
    });
}

$(document).on('click', 'button', appendResize);


This allows you to create as many buttons/template combinations as you like without having to change the javascript.