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!

4 programmer comments:

jipigi@gmail.com 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.