Can I make a textarea grow with text to a max height?
Asked Answered
P

6

36

I'm working on a project where I have data in divs that can be various sizes. When a user clicks on one of the divs, it needs to turn into an editable textarea. The width is constant, but I'd like the height to start as the height of the original div and then grow to a max height before adding a scrollbar. Is that possible?

Prowel answered 5/4, 2013 at 22:48 Comment(0)
F
67

You can use contenteditable and let the user input in a straight div, here's a demo: http://jsfiddle.net/gD5jy/

HTML

<div contenteditable>
    type here...
</div>

CSS

div[contenteditable]{
    border: 1px solid black;
    max-height: 200px;
    overflow: auto;
}
Floruit answered 5/4, 2013 at 22:59 Comment(5)
Be aware the contenteditable renders completely different HTML on different browsers, especially when it comes to line breaks.Undermine
@DanielAllenLangdon's right. I substituted pre for div and got the line breaking and wrapping I wanted in Chrome. When I saw his comment, I checked Firefox and ended up having to add white-space: pre-wrap to my CSS. I didn't try other browsers.Hate
What if I cant use contenteditable due to React restrictions? Aaand I can't use Draft.js either because of delayed state updates.Asynchronism
does this contenteditable div accept any dom event? how would I capture change of the innerHTML in this div?Plummy
This is not a valid answer. A contenteditable div cannot do what a text area can.Campball
B
8

There's an excellent A List Apart article on this topic: Expanding Text Areas Made Elegant

Benevolent answered 19/3, 2015 at 5:13 Comment(1)
Thanks for the link! Great article. I think you should at least explain in a couple of sentences how the author does it - to give readers some context before they click the link. Otherwise your post would be better as a comment according to Stack Overflow etiquette. Also, to save people time debugging, I needed to change container.className += "active"; to container.className += " active"; to get the author's code working.Syllable
D
6

Here is the JavaScript function

// TextArea is the Id from your textarea element
// MaxHeight is the maximum height value
function textarea_height(TextArea, MaxHeight) {
    textarea = document.getElementById(TextArea);
    textareaRows = textarea.value.split("\n");
    if(textareaRows[0] != "undefined" && textareaRows.length < MaxHeight) counter = textareaRows.length;
    else if(textareaRows.length >= MaxHeight) counter = MaxHeight;
    else counter = 1;
    textarea.rows = counter; }

here is the css style

.textarea {
height: auto;
resize: none; }

and here is the HTML code

<textarea id="the_textarea" onchange="javascript:textarea_height(the_textarea, 15);" width="100%" height="auto" class="textarea"></textarea>

it works fine for me

Dogged answered 5/4, 2013 at 22:54 Comment(4)
What if the textarea contains no newlines, just wrapping?Rarity
i just copied this code from an older project... but it's possible to change the code to your needs... mabye you can split the code every 40 signsDogged
Bad solution. What if user doesn't use enter?Lefty
Worked for me, with little change in my case. function ResizeTextBox(elm) { var rowcount = $(elm).attr('rows'); var textareaRows = $(elm).val().split("\n"); if (textareaRows[0] != "undefined" && textareaRows.length < rowcount - 1) { counter = rowcount; } else { counter = textareaRows.length + 1; } $(elm).attr('rows', counter) }Cothran
S
1

The best solution I founded (on developer.mozilla.org) with Javascript and adapted to be used in one line and with a bit of style.

The separate Javascript is only useful for automatic writing for the demo.

/*
      AUTO TYPE TEXT FROM THIS S.O. ANSWER: 
          https://mcmap.net/q/427451/-auto-type-inside-text-input
          Author @Mr.G
*/
var demo_input = document.getElementById('txtArea');

var type_this = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sed blandit turpis, eu auctor arcu.\r\n\r\nCras iaculis urna non vehicula volutpat. Nullam tincidunt, ex sit amet commodo pulvinar, lorem ex feugiat elit, non eleifend nisl metus quis erat.";
var index = 0;

window.next_letter = function() {
    if (index <= type_this.length) {
        demo_input.value = type_this.substr(0, index++);
        demo_input.dispatchEvent(new KeyboardEvent('keyup'));
        setTimeout("next_letter()", 50);
    }
}

next_letter();
<!-- THE MAIN PART -->
<textarea 
  id = "txtArea"
  cols="20" 
  rows="4" 
  onkeyup="if (this.scrollHeight > this.clientHeight) this.style.height = this.scrollHeight + 'px';"
  style="overflow:hidden;
         transition: height 0.2s ease-out;">
         
</textarea>
Selmner answered 21/7, 2021 at 10:4 Comment(1)
It doesn't work if the user wants to edit what he just typed and starts adding lines at the start of the text. Since scroll won't be higher than height.Unclinch
H
0

I know that this question is fairly old, but a trick that I have used to dynamically scale textarea is to check if the scrollTop of the textarea element is more than zero since that would mean that it's scrollable. In the event that it's scrollable, simply increment the rows in a while loop while the scrollTop is more than zero...

if(textarea.scrollTop>0){
            while(textarea.scrollTop>0){
                textarea.rows++;
            }
        }
Hogen answered 17/3 at 23:55 Comment(0)
J
-3

Old post but it's the top result on google, so let me share my simple answer.

I just make a function that runs every 200ms, updating the textarea. It's a very easy way to do it, but it works for me.

Ignore the css please! It is just for decoration.

function textarea_height() {
    var textarea = document.getElementById("htmlinput");
  textarea.rows = textarea.value.split("\n").length;
}
setInterval(textarea_height, 200);
#htmlinput {
  border-color: black;
  border-radius: 15px;
  border-width: 3.3px;
  font-family: monospace;
  background-color:lightgray;
  width: calc(98%);
  padding: 5.5px;
}
<html>
<head>
<title> StackOverflowExample </title>
</head>
<body>

  <textarea id="htmlinput">Here is my
  Very Cool
  Text Area
  it even fits
  to the lines of
  the text!</textarea>

</body>
</html>
Jardine answered 20/9, 2022 at 19:39 Comment(1)
This will work, however this is not good approach.Sapphira

© 2022 - 2024 — McMap. All rights reserved.