4

I have a textarea with a fix height of 70px. When I press enter for a new line multiple times I would like to let the height of the textarea grow. At the moment, after the 6th line a scrollbar appears. This makes sense, because of the fix height of 70px. But is there a way to solve this?

textarea {
  min-height: 70px;
}
<textarea>Hello World! Click "enter" for more lines...</textarea>
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
webta.st.ic
  • 4,781
  • 6
  • 48
  • 98

2 Answers2

4

you can handle this with a simple javascript function, take a look at the snippet:

var textarea = document.getElementById('txtArea');

textarea.addEventListener('keydown', autosize);
             
function autosize(){
  var el = this;  
    setTimeout(function(){
      el.style.cssText = 'height:auto; padding:0';
      el.style.cssText = 'height:' + el.scrollHeight + 'px';
    },0);
  
}
textarea {
  min-height: 70px;
  overflow: hidden;
}
<textarea id="txtArea">Hello World! Click "enter" for more lines </textarea>

ALSO, if you want to, you can add a max height, here is the snippet:

var textarea = document.getElementById('txtArea');

textarea.addEventListener('keydown', autosize);
             
function autosize(){
  var el = this;
  el.style.cssText = 'overflow: hidden !important';
  
  if (el.scrollHeight > 120){
      el.style.cssText = 'overflow: scroll !important';
      el.style.cssText = 'height: 120px';
      textarea.removeEventListener('keydown', autosize);
  }else{
    setTimeout(function(){
      el.style.cssText = 'height:auto; padding:0';
      el.style.cssText = 'height:' + el.scrollHeight + 'px';
    },0);
  }
}
textarea {
  min-height: 70px;
}
<textarea id="txtArea">Hello World! Click "enter" for more lines </textarea>
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
  • 1
    This seems to be the best way to solve it for textarea. I made an example with pure css but without textarea: https://codepen.io/STWebtastic/pen/EoLJKz Just use contenteditable elements, then it works also. Notice: If you take this solution, you can't set the property `resize` like you can do it with textareas. You will have to write JS for such a solution. Thanks. – webta.st.ic Jan 12 '18 at 08:46
0

if you want to use only css you can also create your element like this:

function contentTransfer(){
  document.getElementsByClassName("container")[0].innerHTML = document.getElementById("myTextArea").innerHTML;
}
.custom_textArea{
  min-height: 70px;
  border: 1px solid lightGray;
  padding: 7px;
  border-radius: 7px;
  outline: none;
}

.custom_textArea:focus{
  border: 1px solid darkGray;
}
<p id="myTextArea" class="custom_textArea" contenteditable="true">my text</p>
<button onclick="contentTransfer()">get content</button>
<p class="container"></p>
erfanilaghi
  • 206
  • 3
  • 12
  • and if you want to use it with a form that html itself submit it you can use a hidden `input` or `textarea` and `` as your submit button. – erfanilaghi Aug 26 '23 at 05:56