Text Area Auto Resize (on change)

Changes the height of your textarea to zero and then the scroll height to match the height of the text. This version waits until the changed event to fire the shrinking

by Wray Bowling

HTML

<textarea title="First" placeholder="First" autocomplete="off">First</textarea><textarea title="Second" placeholder="Second" autocomplete="off">Second</textarea><textarea title="Third" placeholder="Third" autocomplete="off">Third</textarea><textarea title="Fourth" placeholder="Fourth" autocomplete="off">Fourth!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</textarea>

CSS

*{margin:0; padding:0 border:0}
body{ background-color:#badbad; }
textarea{
    width:120px;
    padding:0;
    overflow:hidden;
    font-family: Helvetica, Arial, sans-serif;
    font-size:20px;
    background-color:orange;
    resize: none;
    word-wrap: break-word;
    white-space: pre-wrap;
}

JavaScript

// run this after every key press
jQuery.fn.expandTextarea = function(e) {
    // be sure to subtract the padding+border+margin
    $(this).height(this[0].scrollHeight);
    if(e.keyCode == 13){
        e.preventDefault();
    }
};

// run this after the textarea hasn't been played with for a while
jQuery.fn.contractTextarea = function() {
    // be sure to subtract the padding+border+margin
    $(this).height(0).height(this[0].scrollHeight);
};

$(document).ready(function(){
    $("textarea").live('keydown keyup', function(e){
        $(this).expandTextarea(e);
    });
    
    $("textarea").live('change', function(){
        $(this).contractTextarea();
    });
    
    $("textarea").each(function(){
        $(this).contractTextarea();
    });
});