October 30, 2019
Issues we've come across, and how we fixed them.
How To Auto-Grow A Text Area

We were messing around with the admin side of things and we discovered that our textareas were not behaving the way we wanted them to. We want them to grow when you type into them, automatically. We had this complicated code written out to accomplish this, but we thought, "there's gotta be a better way." So here's the new code.

  • <textarea></textarea>
  • <script>
  • $('textarea').each(function(){
  • var that = $(this);
  • that.css('box-sizing','border-box'); //-> required to get the correct height of input
  • function resizeInput(){ //-> create function so we can place it in many different locations
  • that.stop(true,true).animate({
  • 'min-height':that.get(0).scrollHeight
  • });
  • }
  • resizeInput(); //-> resize on page load
  • that.off('keydown').on('keydown',function(){ //-> resize when you type, keydown is efficient
  • resizeInput();
  • });
  • });
  • </script>

We want this to apply to every single textarea that's on our pages. For some reason you have to make sure that the 'box-sizing' attribute is set to 'border-box'. Instead of checking first, we'll just set the attribute so there's no confusion in the future. Then you set the height to the scroll height you find using jQuery. We set the min-height to that so we can still resize the box bigger if we want to. This might be personal preference, but sometimes while we work in a textarea we like to give ourselves extra room to type things. Setting the min-height to the scroll height will allow us to make it bigger if we choose to.

We use the animate function so that it looks a little nicer, but you can use .css({}); if you want it to happen quicker.

 Profile Picture

Proudly Serves

Allentown, Bethlehem, Lehigh Valley... and everywhere else!

Follow Our Socials