Auto grow textarea

Text area that auto grows.

by Kees C. Bakker

HTML

<textarea id="tst" rows="1" cols="40">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum porttitor neque eget consequat. Sed faucibus purus vitae felis facilisis bibendum.</textarea>

<br/>
<br/>
<button id="Add">Add one</button>
<button id="Add2">Add another</button>
<div id="pane">

</div>


<br/>
<br/>
For more info: <br/>
<a href="http://stackoverflow.com/questions/4717635/jquery-building-an-autoresizing-textarea-that-doesnt-flash-on-resize">Building an AutoResizing TextArea that Doesn't Flash on Resize</a><br/>
<a href="http://stackoverflow.com/questions/4768691/how-bind-the-scroll-event-on-a-live">How bind the scroll event on a Live()?</a><br/>

CSS

textarea{    
    overflow:hidden;
    overflow-x:hidden;
    overflow-y:hidden;
    padding:10px;
}

JavaScript

$('#Add').click(function(){
   $('#pane').append($('<textarea class="new" rows="1" cols="40"></textarea><br/>'));
    $('textarea:last').focus();
});

$('#Add2').click(function(){
   $('#pane').append($('<textarea class="new" rows="1" cols="40">Some text</textarea><br/>'));
    $('textarea:last').focus();
});

//inital resize
resizeTextArea($('#tst'));

//'live' event
$('textarea').live('keyup', function() {
    var elem = $(this);
    
    //bind scroll
    if(!elem.data('has-scroll'))
    {
        elem.data('has-scroll', true);
        elem.bind('scroll keyup', function(){
            resizeTextArea($(this));
        });
    }
            
    resizeTextArea($(this));
});

//resize text area
function resizeTextArea(elem) {
    elem.height(1); 
    elem.scrollTop(0);
    elem.height(elem[0].scrollHeight - elem[0].clientHeight + elem.height());
}