Muchas veces necesito poner un textarea que aparente ser un input de tipo texto, pero que ajuste su altura a su contenido.
Gmail tiene implementada esta funcionalidad en el campo de destinatarios en la redacción de un email.
Para conseguir un efecto parecido he creado esta función (necesita jQuery para funcionar):
function setTextareaHeight(textareas) {
textareas.each(function () {
var textarea = $(this);
if ( !textarea.hasClass('autoHeightDone') ) {
textarea.addClass('autoHeightDone');
var extraHeight = parseInt(textarea.css('padding-top')) + parseInt(textarea.css('padding-bottom')), // to set total height - padding size
h = textarea[0].scrollHeight - extraHeight;
// init height
textarea.height('auto').height(h);
textarea.bind('keyup', function() {
textarea.removeAttr('style'); // no funciona el height auto
h = textarea.get(0).scrollHeight - extraHeight;
textarea.height(h+'px'); // set new height
});
}
})
}
y llamo a la función en el document ready:
$(function(){
setTextareaHeight($('textarea'));
})
