4

I set the width of a textarea to 100%, but now I need to know how many characters can fit in one row.

I'm trying to write a javascript function to auto-grow/shrink a textarea. I'm trying to keep from using jquery since I just need this one function.

My logic is to rows = textarea.value.split('\n'), iterate through rows and count += rows[i].length/textarea.cols, then count += rows.length, and finally textarea.rows = count. The only problem is that count is too large because textarea.cols is too small.

DanMan
  • 11,323
  • 4
  • 40
  • 61
sehwoo
  • 41
  • 1
  • 1
  • 2
  • 4
    This is a tough problem. For most fonts, it is impossible to predict a fixed number of allowed characters because each character has a different width. You will need to use a monospaced font like courier to do this – Pekka Dec 28 '10 at 17:50
  • 1
    Why use JavaScript? Can you use CSS? #textareaId { width:100%; } – brildum Dec 28 '10 at 17:55
  • 1
    @Pekka - always enjoying reading your answers/comments – ifaour Dec 28 '10 at 18:09
  • 1
    @ifaour thank you! It still is fun to write here, or even just think aloud in comments. – Pekka Dec 28 '10 at 22:55
  • 1
    Possible duplicate of [Creating a textarea with auto-resize](http://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize) – DanMan Nov 06 '15 at 11:36

2 Answers2

7

This function will set the height of the element (textarea, in your case) to the browser's default height. If that causes a scrollbar to appear, the height will be switched to the actually needed height.

function autoHeight(element){
    element.style.height='auto';
    element.style.height=element.scrollHeight+'px';
}

If you don't like the browser's default height, you can change that to some other default value of your own, of course.

DanMan
  • 11,323
  • 4
  • 40
  • 61
  • 2
    +1 for one of the best answers on the subject I have found. The only one thing that I would change is to use `element.style.height=0;` to make sure the `textarea` height is as little as possible. Otherwise, in case of the browser I am using, it is at least two rows. – Grzegorz Nov 30 '13 at 02:58
  • 1
    Thanks. You could also add a `minHeight` parameter to the function. A height of 0 might cause flickering, if you use this in a keyup event, for example. – DanMan Dec 01 '13 at 14:50
  • 1
    Best solution I've seen so far! – Jeremy Jul 21 '20 at 21:17
1

Try this and enjoy:

var textarea = document.getElementById("YourTextArea");
var limit = 50; //height limit

textarea.oninput = function() {
  textarea.style.height = "";
  textarea.style.height = Math.min(textarea.scrollHeight, limit) + "px";
};
textarea {
    width: 99%;
}
<textarea id="YourTextArea"></textarea>