3

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,087
  • 3
  • 20
  • 46
webta.st.ic
  • 4,312
  • 3
  • 45
  • 91

1 Answers1

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,087
  • 3
  • 20
  • 46
  • 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