Search code examples
javascripthtmlcssheighttextarea

Make textarea with setted height grow when new line is added


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>


Solution

  • 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>