Adjusting automatically the height of the textarea as you type – as seen on Facebook
January 6, 2010 No CommentsI am sure you have seen it on facebook and some other sites. You start typing into the textarea and when there is almost no room left for your text then the textarea adjusts the height and you can continue typing more text without getting the scroll bar on the right.
I have build this function almost into the plugin stage but you can just simple grab the whole code and adjust the first 4 variables and you are ready to go.
(You can see working example on lewro.com)
$(function(){
$textarea = $('#contact_us_wrapper form textarea'); // Set the textarea (it could simple be just $('textarea') and it would be applied to all of them across this site
$characterLimit = 105; // Maximum number of characters in single line
$originalHeight = $($textarea).css("height").replace("px",""); // Height of single line (without 'px')
$animateTime = 500; // Set the time for animation
$textarea.keyup(function(){
$currentCharacters = $($textarea).val().length; // Actual amount of characters
$heightRatio = $currentCharacters / $characterLimit; // Get the ratio of characters
$roundRatio = Math.round($heightRatio); // Round the ration so it can be used for new height calculation
if($currentCharacters > $characterLimit){
// Calculate new height for textarea
$newHeight = (parseInt($originalHeight)) * $roundRatio + "px";
// Set the new heights
$($textarea).stop().animate({height: $newHeight}, $animateTime);
}else{
$($textarea).stop().css({height: $originalHeight});
}
});
});