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:
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 ?
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.
Couldn't you use this code in combination with a short character counting function and simple math? I like the original idea ;)
Character counting only will work if you use a fixed width font.
Post a Comment