Textarea auto re-size function….

So I had to create an auto re-size function for textareas. I looked around on the net and found a few things, but nothing really did what i wanted…. so I wrote this quick and dirty function to determine the pixel height a textarea should be based on the number of new lines and length of the content in that textarea. You pass the function the id of the textarea and it returns a number which you should resize the textarea’s pixel height to. The function uses prototype element functions, but these could easily be ported to another framework or replaced with crossbrowser javascript code. I’m just too lazy…..you get the idea =)

 
sizeTextarea = function(textarea){ 
	textarea = $(textarea);
	var hard_lines = 0;
	var soft_lines = 0;
	var lines = 0;
	var str = textarea.value;
	var w = textarea.getWidth();
	var fs = parseInt(textarea.getStyle('font-size').replace('px',''));
	var lh = parseInt(textarea.getStyle('line-height').replace('px',''));
	var tmp_char_cnt = 0;
	var tmp_s = '';
	var sarr = str.split("\n");
	hard_lines = sarr.length;
	if(sarr.length>0){
		for(i=0;i<sarr.length;i++) {
			tmp_s = sarr[i].split('');
			tmp_char_cnt = (tmp_s.length*6)/w;
			if(tmp_char_cnt > 1){
				soft_lines += tmp_char_cnt;
			}
		}
	}
 
	lines = hard_lines+soft_lines+1;
	return (lines*lh); 
}

You may need to change this line:

tmp_char_cnt = (tmp_s.length*6)/w;

as I found the number 6 just seemed to work for me with the font size in my textarea…..good luck! I hope someone finds this useful….

1 Comment to Textarea auto re-size function….

  1. vincent's Gravatar vincent
    February 1, 2011 at 7:52 am | Permalink

    well, it does work under firefox 3.6, ie 8 works fine.

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>