0

My JS is limited, and I am having trouble replicating <textarea> functionality I have seen in the Materialize framework (scroll to the <textarea> section).

I essentially want my <textarea> to expand smoothly based on the .val() of the <textarea>. Exactly like the example in the link I provided.

My code is below:

$('textarea').keyup(function() {
  $(this).animate({height: 'auto'}, 250);
  $(this).height(this.scrollHeight);
});

Thanks in advance.

DanMad
  • 1,643
  • 4
  • 23
  • 58
  • Take a look at the [code they use](https://github.com/Dogfalo/materialize/blob/master/js/forms.js#L121-L187) or take a look at [this answer](http://stackoverflow.com/a/1761203/145346) on how to get the number of rows in a textarea; once you have that, you can calculate the height. – Mottie May 06 '17 at 16:26

1 Answers1

0

With your code, you are adding an automatic height at the first keyup(), then on the next keyup() it will still be auto.

I think you have to get the line number like this stack, get the line-height, and calculate the appropriate height for each keyupand keydown.

So maybe something like this (missing a moving scroll fix I think) :

// Should be in a JS utility file
String.prototype.lines = function() {
  return this.split(/\r*\n/);
}
String.prototype.lineCount = function() {
  return this.lines().length;
}

// The code
$(document).on('keyup keydown', 'textarea', function () {
  var loElem = $(this),
    lsValue = loElem.val();
  loElem.animate({minHeight: lsValue.lineCount() * 14}, 250);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<textarea></textarea>
Community
  • 1
  • 1
Quentame
  • 254
  • 1
  • 4
  • 13