-2

I want to create a textarea which is preloaded with content. Its height should be auto when content is there but when it's empty the height should become 4.2rem. When I enter text in it should increase and decrease the height to a maximum height of 7.7rem using jQuery.

How can I do this?

.textAreaGrow {
  padding: 1.8rem 0 .8rem;
  height: 4.2rem;
  max-height: 7.7rem;
}
<textarea class="textAreaGrow">Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.</textarea>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
ajay
  • 53
  • 7
  • Auto? As in `height:auto` or assuming the height of the content? – Spectric May 12 '21 at 15:33
  • Hi Spectric, thanks for reply, i want preloaded content height but maximum height should be 7.7rem(77px) – ajay May 12 '21 at 15:40
  • Not sure if this would help... https://stackoverflow.com/questions/17772260/textarea-auto-height – Kinglish May 12 '21 at 15:40
  • What stopped you from doing a small research i.e: [Resize textarea on input](https://stackoverflow.com/questions/57953324/resize-textarea-on-input) and applying some Math.max() – Roko C. Buljan May 12 '21 at 18:00

2 Answers2

0

The trick here is to set the height of the textarea to the scrollHeight of the element when it has a height of around 0px everytime the user inputs into the textarea.

We can add another if statement to check whether the textarea is empty. If it is, set the height to its initial height.

$(document).ready(function() {
  let txtArea = $('.textAreaGrow');
  txtArea.on('input', updateHeight);

  function updateHeight() {
    let t = txtArea;
    if (t.val().trim() == "") {
      t.css('height', '4.2em');
    } else {
      t.css('height', '0.1px');
      t.css('height', t[0].scrollHeight);
    }
  }
  updateHeight();
})
.textAreaGrow {
  height: 4.2rem;
  max-height: 7.7rem;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="textAreaGrow">Preloaded text

With newlines too??</textarea>
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

An alternative could be to use another element than textarea. And then give the element the attribute contenteditable. Then it is easier to control the styles. But then you lack the functionallity of a form element like textarea. So, it depends on what the element should be used for.

.textAreaGrow {
  border: thin gray solid;
  padding: 1.8rem 0 .8rem;
  width: 20em;
  min-height: 4.2rem;
  max-height: 7.7rem;
  overflow: scroll;
}
<div class="textAreaGrow" contenteditable>
  Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.
</div>
chrwahl
  • 8,675
  • 2
  • 20
  • 30