Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize textarea after deleting text

If you write text, a textarea increases in size, but when you delete this text then nothing happens. Is it possible to dynamically decrease the height of a textarea if you are deleting text?

$('textarea').on('input', function() {
  var scrollHeight = parseInt($(this).prop('scrollHeight'));
  $(this).height(scrollHeight);
});
.OuterDiv
{
  width:200px;
  height:300px;
  border:1px solid #000;
  position:relative;
  bottom:0;
}
.text
{
  resize:none;
  width:198px;
  height:45px;
  max-height:145px;
  background-color:rgba(90,90,180,1);
  font-size:16px;
  font-family:Arial;
  overflow-y:auto;
  padding:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="OuterDiv">
  <textarea class="text" placeholder="Write some text..."></textarea>
</div>
like image 937
PiotrS Avatar asked Dec 24 '22 23:12

PiotrS


1 Answers

Set the height style instead of the property, and use an initial height so as to always start at 45px.

$('textarea').on('input', function() {
    $(this).css('height', "45px");
    $(this).css('height', this.scrollHeight+"px");
});
.OuterDiv
{
  width:200px;
  height:300px;
  border:1px solid #000;
  position:relative;
  bottom:0;
  }
.text
{
  resize:none;
  width:198px;
  height:45px;
  max-height:145px;
  background-color:rgba(90,90,180,1);
  font-size:16px;
  font-family:Arial;
  overflow-y:auto;
  padding:0;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="OuterDiv">
  <textarea class="text" placeholder="Write some text..."></textarea>
</div>
like image 112
adeneo Avatar answered Dec 31 '22 13:12

adeneo