The scrollHeight is the distance between the top and bottom edges of the object’s content. But the height differs in various browsers.

For MSIE, the scrollHeight of a textarea is the real height of the content that you input just now including the paddings, while scrollHeight in Opera excludes the paddings.

But in Firefox and especially in Safari, the scrollHeight turns out a bit weirdly. The scrollHeight of a textarea in firefox will be larger than or equal to the css height of the textarea, even if you have little input.

Smart TextArea

When we post comments on others’ blogs or somewhere, there’re often too many lines so that we should drag the scrollbar up and down to check our input, making it much inconvenient for us.

So I wanna make a flexible textarea which can automatically adjust its own height with the content people input in, instead of showing a mechanical scrollbar.

Concepts:
Set the height of the textarea equal to the scrollHeight.
As the matter of Firefox and Safari, it doesn’t work when we want to reduce the height, so let’s have our idea fixed.

HTML:

1
2
3
4
5
6
<form>
	<div>
		<textarea name="comment" id="comment" rows="6" tabindex="4" cols="7">
		</textarea>
	</div>
</form>

We put a div out of the textarea, why?

To get the real height of the content, we have to set the textarea with no-height, so that we can get the desired value of scrollHeight.

jQuery way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$( '#comment' ).keyup( function(){ setTextareaHeight(); } );
function setTextareaHeight(){
	if( !this._browser ){
		//get browser info.
		//decide whether padding should be taken into account
		this._browser = $.browser.msie || $.browser.safari;
		this._padding = setPreview._browser ?
			( parseInt( $( '#comment' ).css( 'padding-top' ) ) +
			parseInt( $( '#comment' ).css( 'padding-bottom' ) ) ) : 0;
	}
 
	var comHeight = $( '#comment' ).height();
 
	//100 is the minimun height we want.
	if( comHeight > 100 ){
		//This is important!
		//We fixed the height of the div,
		//so that the page will not be twinkling
		$( '#comment' ).parent().css('height', $( '#comment' ).height() + 'px' );
 
		//set the height to zero to get the real content height
		$( '#comment' ).height(0);
	}
 
	var comScrollHeight = $( '#comment' ).get(0).scrollHeight - this._padding;
 
	if ( comScrollHeight > 100 )
		$( '#comment' ).height(comScrollHeight);
	else if( comHeight > 100 )
		$( '#comment' ).height(100);
 
	$( '#comment' ).parent().css('height', 'auto');
}

Just try to type in my textarea below.

If you have a better solution, you might as well share with us, which will be awfully appreciated!

    Tested with:
  • Internet Explorer 6.0 – 8.0
  • Firefox 3.0 – 3.5
  • Safari 4.0
  • Opera 9.64