PiotrS PiotrS - 14 days ago 9
CSS Question

Hide textarea after delete text

If you write text, text area is increasing, but when you delete this text then nothing happen. Is possible dynamically decrease height text area if you 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>




Answer

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>