Changing height of an element to fit content

Changing height of an element to fit content

I have this script that makes the height of an element with an [data-resize] attribute grow and shrink so that it always fits the content:

  1. var maxHt = 100;

  2. $.each($('[data-resize]'), function(e) {
  3.   var offset = this.offsetHeight - this.clientHeight;

  4.   $(this).on('keyup', function() {
  5.     if (this.scrollHeight < maxHt)
  6.       $(this).css('height', 'auto')      // not sure why I have to do it like this, but I do...
  7.                 .css('height', this.scrollHeight + offset);

  8.     else
  9.       $(this).css({ 'height'        : maxHt + 'px',
  10.                           'overflow-y' : 'scroll' });
  11.   })
  12.   .removeAttr('data-resize');
  13. });

If I remove lines 7, 11, 12, and 13 then it works perfectly to make the element grow and shrink to infinity. But I don't want it to grow to infinity, I want it to stop growing at a certain point so that the user only has the most relevant content in view.

So the above works OK, except that it doesn't shrink back to the original when they backspace or delete. Which makes sense, because after it has grown past maxHt then  this.scrollHeight is not going to be less than maxHt.

I also tried $(this).height(), this.clientHeight, and this.offsetHeight, but none of them worked correctly.

I have a fiddle so you can see the results:


Can you guys suggest any other way that I could make this work? Is there another attribute that I should use other than this.scrollHeight?