Hello, please sign in or register
You are here: Home

Expanding textarea as you type

solution 1:

Its often that a text area contains more information than is viewable. Here's a simple solution i came up with after reading a few blogs.

<textarea style='overflow-y:hidden;' onkeyup='this.rows = (this.value.split("\n").length||1);'>
</textarea>

This sets the overflow to hidden to avoid displaying the scrollabrs in IE7.

Try it yourself (this is only vertical expansion)

Additionally

To force a minimum number of rows use the Math.max method, ie. in the below code the minimum number of rows would be 5.

Math.max(this.value.split("\n").length,5)

solution 2:

Keep adding rows until the scrollHeight is less than the actual height

The above solution simply counts newline characters to determine how many rows the textarea has. But sentences may also overflow to two or more lines: where the text in the line is longer than the width of the textarea. Hence the below solution, put forward at http://www.webdeveloper.com/forum/archive/index.php/t-61552.html is a more robust solution.

while (
	textArea.rows > 1 &&
	textArea.scrollHeight < textArea.offsetHeight
){
	textArea.rows--;
}

while (textArea.scrollHeight > textArea.offsetHeight)
{
	textArea.rows++;
}
textArea.rows++

Try it yourself Type a sentence which flows over more than one row and the size of the box will increase to accomodate the change.

solution 2 (safe):

Predefined Height

Unfortunatly if the height of the textarea is defined by CSS, then this causes the while loop to crash the browser. - increases the number of rows without effecting the offsetHeight.

The solution here is to check whether the last row increase had an effect, otherwise one could also test if the height had been set.

while (
	textArea.rows > 1 &&
	textArea.scrollHeight < textArea.offsetHeight
){
	textArea.rows--;
}
var h=0;
while (textArea.scrollHeight > textArea.offsetHeight && h!==textArea.offsetHeight)
{
	h=textArea.offsetHeight;
	textArea.rows++;
}
textArea.rows++

 Nice

Comments

anon
best tut on this i've found.. good job
Created 05/05/09
Perfect
No jquery, few and powerful rows of code. Perfect job!
Created 02/12/11
Perfect
Good job... Thanks for share this... :) best of luck
Created 22/05/12
HELP
I am using the second solution just not working ,please help! function expandArea(textArea) { while (textArea.rows > 1 && textArea.scrollHeight < textArea.offsetHeight) { textArea.rows--; } while (textArea.sc...
Created 20/05/13
Malaka
gamiesai re!
Created 21/10/13
Title*
Comment

Prove you are not a robot

To prove you are not a robot, please type in the six character code you see in the picture below
Security confirmation codeI can't see this!
Contact
Name*
Email never shown*
Home Page

Author

Andrew Dodson
Since:Feb 2007

Comment | flag

Categories

Bookmark and Share