Code Snippet

Home » Code Snippets » jQuery » Animate Height/Width to “Auto”

Animate Height/Width to “Auto”

It's not possible to do thing.animate({ "height": "auto" });. So this is Darcy Clarke's method to allow that to work. You essentially clone the element, remove the fixed heights currently inflicting the element, and measure/save the value. Then you animate the real element to that value.

jQuery.fn.animateAuto = function(prop, speed, callback){
    var elem, height, width;
    return this.each(function(i, el){
        el = jQuery(el), elem = el.clone().css({"height":"auto","width":"auto"}).appendTo("body");
        height = elem.css("height"),
        width = elem.css("width"),
        elem.remove();

        if(prop === "height")
            el.animate({"height":height}, speed, callback);
        else if(prop === "width")
            el.animate({"width":width}, speed, callback);
        else if(prop === "both")
            el.animate({"width":width,"height":height}, speed, callback);
    });
}

Usage

$(".animateHeight").bind("click", function(e){
    $(".test").animateAuto("height", 1000);
});

$(".animateWidth").bind("click", function(e){
    $(".test").animateAuto("width", 1000);
});

$(".animateBoth").bind("click", function(e){
    $(".test").animateAuto("both", 1000);
});

Reference URL

Subscribe to The Thread

  1. Colton

    If you are experiencing a resize issue, where the element is (when resized) bigger than it’s parent, replace:

    .appendTo("body");

    with:

    .appendTo(el.parent());

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~