Friday, December 26, 2008

Auto-Grow Textarea - doing it the easy way in Javascript

Just earlier on, I was working on a project for a friend of mine. The project was a php website that includes shopping cart, and some other modules. Well, lately i'm very into facebook and I was fascinated by their auto-growing text boxes. So i googled and found some javascript code snippets too.

However, these scripts either require jQuery javascript framework or use time intervals (window.setInterval) to check for the height. These techniques made it look very ugly: and high resource usage too.

Here, by combining String Object match method and textarea's onkeydown event, I can do it neatly in one line.

<textarea onkeypress="var m = this.value.match(/\n/g); if(m!=null) {this.rows = (m.length+1);}else{this.rows = 2;}"></textarea>

Upon each key press, the javascript code will check for the number of newline characters in the text area value. If there's no match, it will set to the default.

See, it's better than installing jQuery framework just to do this auto-grow textarea! and you can do it selectively too!

To apply this to all textarea DOM object, you can use jQuery to do so.
<script type="text/javascript">/* <![CDATA[ */ $(document).ready(function(){$("textarea").keypress(function(e){var m = this.value.match(/\n/g); if(m!=null) {this.rows = (m.length+1);}else{this.rows = 2;}});});/* ]]> */</script>

The code will work no matter where you place in the body, because the applying of keypress binding will only start when the whole document is loaded. Hope the new code helps!

7 comments: said...

What about the automatic word wrapping done by the textarea ?
A big sentence can display on multiple lines in the textarea without any cariage return in it and your script won't autogrow accordingly, no ?

thephpdeveloper said...

jipigi - since this code only checks for newline, wordwarps are not taken into consideration. what you are saying is right. I didn't cater for word warps.

Robert said...

Couldn't you use this code in combination with a short character counting function and simple math? I like the original idea ;)

Guinevere said...

Character counting only will work if you use a fixed width font.

thephpdeveloper said...

@Robert and @Guinevere

yep if you want to do character counting, you will need fixed with font.

analytics said...

Simple and nice. There's a way to set a max-height, you need to edit this way:

... onkeypress="var m = this.value.match(/\n/g); if(m.length>=20) {this.rows = 20;} else if(m!=null) {this.rows = (m.length+1);} else{this.rows = 2;}" ...

and the textare will stop growing whent a 20 rows height has been reached.

john wright said...

I have read your blog its very attractive and impressive. I like it your blog.

PHP 7 Training in chennai | PHP 7 Training Course

PHP 7 Training in chennai | Online PHP 7 Course