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!