Search code examples
javascriptjquerytextareaheight

textarea auto height if value is set programatically


firstly I was expecting textarea css height:auto to make it really height:auto i.e. matched to content
shortly - it doesn't work

here is my js way to make it height:auto
problem - it only works if I type inside the textarea and not if I set the value by clicking on a button

$('.btx').on('input', function(){
    $(this).css('height', 'auto').height(this.scrollHeight + 'px');
});

$('button').on('click', function(){
  $('.btx').val("lorem\nipsum\ndolor\nsit\namet");
  $('.btx').css('height', 'auto').height(this.scrollHeight + 'px');
});
.btx{
    display:block;
    width:100%;
    resize:none;
    padding:9px 20px;
    line-height:25px;
    font-family:courier;
    overflow:hidden;
    background:orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
<textarea class='btx'></textarea>


Solution

  • Besides @Rory McCrossan's answer, as you already define an input event, I suggest triggering the input after you click the button.

    $('.btx').on('input', function(){
        $(this).css('height', 'auto').height(this.scrollHeight + 'px');
    });
    
    $('button').on('click', function(){
      $('.btx').val("lorem\nipsum\ndolor\nsit\namet");
      $('.btx').trigger('input');
    });
    .btx{
        display:block;
        width:100%;
        resize:none;
        padding:9px 20px;
        line-height:25px;
        font-family:courier;
        overflow:hidden;
        background:orange;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button>CLICK</button>
    <textarea class='btx'></textarea>