Autoresize textarea
May 28, 2008 4:11 pm JavascriptI was looking for a javascript which could automatically resize a textarea but the ones I’ve found were a bit buggy or ugly, so I’ve written mine. There’s just a tiny bug with copy/paste with mouse.
function autoresize(txtbox)
{
var cols = txtbox.cols ;
var content = txtbox.value ;
var lineCount = 0 ;
var lastEOL = -1 ;
do {
var begin = lastEOL+1 ;
lastEOL = content.indexOf("\n",lastEOL+1) ;
var line = "" ;
if(lastEOL != -1) {
line = content.substring(begin,lastEOL) ;
} else {
line = content.substring(begin,content.length) ;
}
var rows_in_line = Math.floor(line.length/cols)+1 ;
lineCount += rows_in_line
} while (lastEOL != -1) ;
txtbox.rows = lineCount ;
}
and html code :
<textarea name="my_textbox" onkeyup="autoresize(this)" onmouseup="autoresize(this)" rows="24" cols="80"></textarea>
