qadenza
qadenza

Reputation: 9293

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>

Upvotes: 0

Views: 123

Answers (2)

ikhvjs
ikhvjs

Reputation: 5947

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>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because in the button event handler this will be the button, not the .btx element, so you're reading the scrollHeight from the wrong place.

I'd suggest caching a reference to .btx in a variable which you can then refer back to in order to set/get the properties you need. Try this:

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

$('button').on('click', function() {
  $btx
    .css('height', 'auto')
    .val("lorem\nipsum\ndolor\nsit\namet")
    .height($btx.get(0).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>

Upvotes: 1

Related Questions