Auto expand a textarea using jQuery

Jquery

Jquery Problem Overview


How can I make a textarea automatically expand using jQuery?

I have a textbox for explaining the agenda of the meeting, so I want to expand that textbox when my agenda's text keep growing that textbox area.

Jquery Solutions


Solution 1 - Jquery

If you dont want a plugin there is a very simple solution

$("textarea").keyup(function(e) {
    while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
	    $(this).height($(this).height()+1);
    };
});

See it working in a jsFiddle I used to answer another textarea question here.

To answer the question of doing it in reverse or making it smaller as text is removed: jsFiddle

>And if you do want a plugin

@Jason has designed one here

Solution 2 - Jquery

I have tried lots and this one is great. Link is dead. Newer version is available here. See below for old version.
You can try by pressing and hold enter key in textarea. Compare the effect with the other auto expanding textarea plugin....

edit based on comment

$(function() {
   $('#txtMeetingAgenda').autogrow();
});

note: you should include the needed js files...

To prevent the scrollbar in the textarea from flashing on & off during expansion/contraction, you can set the overflow to hidden as well:

$('#textMeetingAgenda').css('overflow', 'hidden').autogrow()




Update:

The link above is broken. But you can still get the javascript files here.

Solution 3 - Jquery

Grows / Shrinks textarea. This demo utilizes jQuery for event binding, but it's not a must in any way.
(no IE support - IE doesn't respond to rows attribute change)

DEMO PAGE


HTML

<textarea class='autoExpand' rows='3' data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>

CSS

textarea{  
  display:block;
  box-sizing: padding-box;
  overflow:hidden;

  padding:10px;
  width:250px;
  font-size:14px;
  margin:50px auto;
  border-radius:8px;
  border:6px solid #556677;
}

javascript (updated)

$(document)
	.one('focus.textarea', '.autoExpand', function(){
		var savedValue = this.value;
		this.value = '';
		this.baseScrollHeight = this.scrollHeight;
		this.value = savedValue;
	})
	.on('input.textarea', '.autoExpand', function(){
		var minRows = this.getAttribute('data-min-rows')|0,
			rows;
		this.rows = minRows;
		rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
		this.rows = minRows + rows;
	});

Solution 4 - Jquery

You can try this one

$('#content').on('change keyup keydown paste cut', 'textarea', function () {
        $(this).height(0).height(this.scrollHeight);
    }).find('textarea').trigger("change");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
  <textarea>How about it</textarea><br />
  <textarea rows="5">111111
222222
333333
444444
555555
666666</textarea>
</div>

Solution 5 - Jquery

Solution 6 - Jquery

Thanks to SpYk3HH, I started with his solution and turned it into this solution, which adds the shrinking functionality and is even simpler and faster, I presume.

$("textarea").keyup(function(e) {
	$(this).height(30);
	$(this).height(this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth")));
});

Tested in current Chrome, Firefox and Android 2.3.3 browser.

You may see flashes of the scroll bars in some browsers. Add this CSS to solve that.

textarea{ overflow:hidden; }

Solution 7 - Jquery

To define a auto expandable textarea, you have to do two things:

  1. Expand it once you click Enter key inside it, or type content more than one line.
  2. And shrink it at blur to get the actual size if user has entered white spaces.(bonus)

Here is a handmade function to accomplish the task.

Working fine with almost all browser ( < IE7 ). Here is the method:

    //Here is an event to get TextArea expand when you press Enter Key in it.
    // intiate a keypress event
    $('textarea').keypress(function (e) {  
       if(e.which == 13)   {   
       var control = e.target;                     
       var controlHeight = $(control).height();          
      //add some height to existing height of control, I chose 17 as my line-height was 17 for the control    
    $(control).height(controlHeight+17);  
    }
    }); 
    
$('textarea').blur(function (e) {         
    var textLines = $(this).val().trim().split(/\r*\n/).length;      
    $(this).val($(this).val().trim()).height(textLines*17);
    });

HERE is a post about this.

Solution 8 - Jquery

I've used the Textarea Expander jQuery plugin before with good results.

Solution 9 - Jquery

Everyone should try this jQuery plugin: xautoresize-jquery. It's really good and should solve your problem.

Solution 10 - Jquery

function autosize(textarea) {
    $(textarea).height(1); // temporarily shrink textarea so that scrollHeight returns content height when content does not fill textarea
    $(textarea).height($(textarea).prop("scrollHeight"));
}

$(document).ready(function () {
    $(document).on("input", "textarea", function() {
        autosize(this);
    });
    $("textarea").each(function () {
        autosize(this);
    });
});

(This will not work in Internet Explorer 9 or older as it makes use of the input event)

Solution 11 - Jquery

I just built this function to expand textareas on pageload. Just change each to keyup and it will occur when the textarea is typed in.

// On page-load, auto-expand textareas to be tall enough to contain initial content
$('textarea').each(function(){
	var pad = parseInt($(this).css('padding-top'));
	if ($.browser.mozilla) 
		$(this).height(1);
	var contentHeight = this.scrollHeight;
	if (!$.browser.mozilla) 
		contentHeight -= pad * 2;
	if (contentHeight > $(this).height()) 
		$(this).height(contentHeight);
});

Tested in Chrome, IE9 and Firefox. Unfortunately Firefox has https://bugzilla.mozilla.org/show_bug.cgi?id=576976">this bug which returns the incorrect value for scrollHeight, so the above code contains a (hacky) workaround for it.

Solution 12 - Jquery

I fixed a few bugs in the answer provided by Reigel (the accepted answer):

  1. The order in which html entities are replaced now don't cause unexpected code in the shadow element. (The original replaced ">" by "&ampgt;", causing wrong calculation of height in some rare cases).
  2. If the text ends with a newline, the shadow now gets an extra character "#", instead of having a fixed added height, as is the case in the original.
  3. Resizing the textarea after initialisation does update the width of the shadow.
  4. added word-wrap: break-word for shadow, so it breaks the same as a textarea (forcing breaks for very long words)

There are some remaining issues concerning spaces. I don't see a solution for double spaces, they are displayed as single spaces in the shadow (html rendering). This cannot be soved by using &nbsp;, because the spaces should break. Also, the textarea breaks a line after a space, if there is no room for that space it will break the line at an earlier point. Suggestions are welcome.

Corrected code:

(function ($) {
    $.fn.autogrow = function (options) {
        var $this, minHeight, lineHeight, shadow, update;
        this.filter('textarea').each(function () {
            $this = $(this);
            minHeight = $this.height();
            lineHeight = $this.css('lineHeight');
            $this.css('overflow','hidden');
            shadow = $('<div></div>').css({
                position: 'absolute',
				'word-wrap': 'break-word',
                top: -10000,
                left: -10000,
                width: $this.width(),
                fontSize: $this.css('fontSize'),
                fontFamily: $this.css('fontFamily'),
                lineHeight: $this.css('lineHeight'),
                resize: 'none'
            }).appendTo(document.body);
            update = function () {
                shadow.css('width', $(this).width());
                var val = this.value.replace(/&/g, '&amp;')
                                    .replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/\n/g, '<br/>')
                                    .replace(/\s/g,'&nbsp;');
                if (val.indexOf('<br/>', val.length - 5) !== -1) { val += '#'; }
                shadow.html(val);
                $(this).css('height', Math.max(shadow.height(), minHeight));
            };
            $this.change(update).keyup(update).keydown(update);
            update.apply(this);
        });
        return this;
    };
}(jQuery));

Solution 13 - Jquery

Code of SpYk3HH with addition for shrinking size.

function get_height(elt) {
	return elt.scrollHeight + parseFloat($(elt).css("borderTopWidth")) + parseFloat($(elt).css("borderBottomWidth"));
}

$("textarea").keyup(function(e) {
	var found = 0;
	while (!found) {
		$(this).height($(this).height() - 10);
		while($(this).outerHeight() < get_height(this)) {
			$(this).height($(this).height() + 1);
			found = 1;
		};
	}
});

Solution 14 - Jquery

This worked for me better:

$('.resiText').on('keyup input', function() { 
$(this).css('height', 'auto').css('height', this.scrollHeight + (this.offsetHeight - this.clientHeight));
});

.resiText {
    box-sizing: border-box;
    resize: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="resiText"></textarea>

Solution 15 - Jquery

People seem to have very over worked solutions...

This is how I do it:

  $('textarea').keyup(function()
  {
    var 
    $this  = $(this),
    height = parseInt($this.css('line-height'),     10),
    padTop = parseInt($this.css('padding-top'),     10),
    padBot = parseInt($this.css('padding-bottom'),  10);
    
    $this.height(0);
    
    var 
    scroll = $this.prop('scrollHeight'),
    lines  = (scroll  - padTop - padBot) / height;

    $this.height(height * lines);
  });

This will work with long lines, as well as line breaks.. grows and shrinks..

Solution 16 - Jquery

For anyone using the plugin posted by Reigel please be aware that this will disable the undo functionality in Internet Explorer (go give the demo a go).

If this is a problem for you then I would suggest using the plugin posted by @richsage instead, as it does not suffer from this problem. See the second bullet point on https://stackoverflow.com/questions/1586931/searching-for-the-ultimate-resizing-textarea for more information.

Solution 17 - Jquery

I wrote this jquery function that seems to work.

You need to specify min-height in css though, and unless you want to do some coding, it needs to be two digits long. ie 12px;

$.fn.expand_ta = function() {

var val = $(this).val();
val = val.replace(/</g, "&lt;");
val = val.replace(/>/g, "&gt;");
val += "___";

var ta_class = $(this).attr("class");
var ta_width = $(this).width();

var min_height = $(this).css("min-height").substr(0, 2);
min_height = parseInt(min_height);

$("#pixel_height").remove();
$("body").append('<pre class="'+ta_class+'" id="pixel_height" style="position: absolute; white-space: pre-wrap; visibility: hidden; word-wrap: break-word; width: '+ta_width+'px; height: auto;"></pre>');
$("#pixel_height").html(val);

var height = $("#pixel_height").height();
if (val.substr(-6) == "<br />"){
    height = height + min_height;
};
if (height >= min_height) $(this).css("height", height+"px");
else $(this).css("height", min_height+"px");
}

Solution 18 - Jquery

There is also the very cool bgrins/ExpandingTextareas (github) project, based on a publication by Neill Jenkins called Expanding Text Areas Made Elegant

Solution 19 - Jquery

I wanted animations and auto-shrink. The combination is apparently hard, because people came up with pretty intense solutions for it. I've made it multi-textarea-proof, too. And it isn't as ridiculously heavy as the jQuery plugin.

I've based myself on vsync's answer (and the improvement he made for it), http://codepen.io/anon/pen/vlIwj is the codepen for my improvement.

HTML

<textarea class='autoExpand' rows='3' data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>

CSS

body{ background:#728EB2; }

textarea{  
  display:block;
  box-sizing: padding-box;
  overflow:hidden;

  padding:10px;
  width:250px;
  font-size:14px;
  margin:50px auto;
  border-radius:8px;
  border:6px solid #556677;
  transition:all 1s;
  -webkit-transition:all 1s;
}

JS

var rowheight = 0;

$(document).on('input.textarea', '.autoExpand', function(){
    var minRows = this.getAttribute('data-min-rows')|0,
        rows    = this.value.split("\n").length;
    $this = $(this);
    var rowz = rows < minRows ? minRows : rows;
    var rowheight = $this.attr('data-rowheight');
    if(!rowheight){
      this.rows = rowz;
      $this.attr('data-rowheight', (this.clientHeight  - parseInt($this.css('padding-top')) - parseInt($this.css('padding-bottom')))/ rowz);
    }else{
      rowz++;
      this.style.cssText = 'height:' + rowz * rowheight + 'px'; 
    }
});

Solution 20 - Jquery

There are a lot of answers for this but I found something very simple, attach a keyup event to the textarea and check for enter key press the key code is 13

keyPressHandler(e){ if(e.keyCode == 13){ e.target.rows = e.target.rows + 1; } }

This will add another row to you textarea and you can style the width using CSS.

Solution 21 - Jquery

Let's say you're trying to accomplish this using Knockout... here's how:

In page:

<textarea data-bind="event: { keyup: $root.GrowTextArea }"></textarea>

In view model:

self.GrowTextArea = function (data, event) {
    $('#' + event.target.id).height(0).height(event.target.scrollHeight);
}

This should work even if you have multiple textareas created by a Knockout foreach like I do.

Solution 22 - Jquery

Simple Solution:

HTML:

<textarea class='expand'></textarea>

JS:

$('textarea.expand').on('input', function() {
  $(this).scrollTop($(this).height());
});
$('textarea.expand').scroll(function() {
  var h = $(this).scrollTop();
  if (h > 0)
    $(this).height($(this).height() + h);
});

https://fiddle.jshell.net/7wsnwbzg/

Solution 23 - Jquery

The simplest solution:

html:

<textarea class="auto-expand"></textarea>

css:

.auto-expand {
    overflow:hidden;
    min-height: 80px;
}

js (jquery):

$(document).ready(function () {
 $("textarea.auto-expand").focus(function () {
        var $minHeight = $(this).css('min-height');
        $(this).on('input', function (e) {
            $(this).css('height', $minHeight);
            var $newHeight = $(this)[0].scrollHeight;
            $(this).css('height', $newHeight);
        });
    });       
});

Solution 24 - Jquery

Solution with pure JS

function autoSize() {
  if (element) {
    element.setAttribute('rows', 2) // minimum rows
    const rowsRequired = parseInt(
      (element.scrollHeight - TEXTAREA_CONFIG.PADDING) / TEXTAREA_CONFIG.LINE_HEIGHT
    )
    if (rowsRequired !== parseInt(element.getAttribute('rows'))) {
      element.setAttribute('rows', rowsRequired)
    }
  }
}

https://jsfiddle.net/Samb102/cjqa2kf4/54/

Solution 25 - Jquery

This is the solution I ended up using. I wanted an inline solution, and this so far seems to work great:

<textarea onkeyup="$(this).css('height', 'auto').css('height', this.scrollHeight + this.offsetHeight - this.clientHeight);"></textarea>

Solution 26 - Jquery

function autoResizeTextarea() {
  for (let index = 0; index < $('textarea').length; index++) {
    let element = $('textarea')[index];
    let offset = element.offsetHeight - element.clientHeight;
    $(element).css('resize', 'none');
    $(element).on('input', function() {
      $(this).height(0).height(this.scrollHeight - offset - parseInt($(this).css('padding-top')));
    });
  }
}

https://codepen.io/nanachi1/pen/rNNKrzQ

this should work.

Solution 27 - Jquery

this worked for me perfectly well

 $(".textarea").on("keyup input", function(){
            $(this).css('height', 'auto').css('height', this.scrollHeight+ 
       (this.offsetHeight - this.clientHeight));
   });

Solution 28 - Jquery

@Georgiy Ivankin made a suggestion in a comment, I used it successfully :) -- , but with slight changes:

$('#note').on('keyup',function(e){
	var maxHeight = 200; 
	var f = document.getElementById('note'); 
	if (f.clientHeight < f.scrollHeight && f.scrollHeight < maxHeight ) 
		{ f.style.height = f.scrollHeight + 'px'; }
	});      

It stops expanding after it reaches max height of 200px

Solution 29 - Jquery

Old question but you could do something like this:

html:

<textarea class="text-area" rows="1"></textarea>

jquery:

var baseH; // base scroll height

$('body')
    .one('focus.textarea', '.text-area', function(e) {
        baseH = this.scrollHeight;
    })
    .on('input.textarea', '.text-area', function(e) {
        if(baseH < this.scrollHeight) {
            $(this).height(0).height(this.scrollHeight);
        }
        else {
            $(this).height(0).height(baseH);
        }
    });

This way the auto resize will apply to any textarea with the class "text-area". Also shrinks when text is removed.

jsfiddle:

https://jsfiddle.net/rotaercz/46rhcqyn/

Solution 30 - Jquery

Try this:

  $('textarea[name="mytextarea"]').on('input', function(){
    $(this).height('auto').height($(this).prop('scrollHeight') + 'px');
  }).trigger('input');

Solution 31 - Jquery

Simple jQuery solution:

$("textarea").keyup(function() {
    var scrollHeight = $(this).prop('scrollHeight') - parseInt($(this).css("paddingTop")) - parseInt($(this).css("paddingBottom"));

    if (scrollHeight > $(this).height()) {
        $(this).height(scrollHeight + "px");
    }
});

HTML:

<textarea rows="2" style="padding: 20px; overflow: hidden; resize: none;"></textarea>

Overflow should be hidden. Resize is none if you do not want to make it resizable by mouse.

Solution 32 - Jquery

You can set the textarea's height to its scrollHeight on all events that change its potential size:

function setTextareaResponsive(id) {
   adjustTextAreaHeight(id);

   $(window).on("resize", function() {
      adjustTextareaHeight(id);
   });

   $("#" + id).on("change input", function() {
      adjustTextareaHeight(id);
   });
}

function adjustTextareaHeight(id) {
   // set height to 1, so scrollHeight is related to linecount, not original textarea size
   $("#" + id).height(1);
   $("#" + id).height(document.getElementById(id).scrollHeight);
}

I personally like it better, when the height is not padded by the extra height (usually 12px) that scrollHeight provides. That's why I like to set the height to the number of lines multiplied by the lineHeight, in which case the function adjustTextareaHeight would look like this:

function adjustTextareaHeight(id) {
   var textarea = document.getElementById(id);

   // set height to 1, so scrollHeight is related to linecount, not original textarea size
   $("#" + id).height(1);
   var lineHeight = parseInt(getComputedStyle(textarea).lineHeight)
   var numberOfLines = Math.floor(textarea.scrollHeight / lineHeight)
   $("#" + id).height(lineHeight * numberOfLines);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPiyushView Question on Stackoverflow
Solution 1 - JquerySpYk3HHView Answer on Stackoverflow
Solution 2 - JqueryReigelView Answer on Stackoverflow
Solution 3 - JqueryvsyncView Answer on Stackoverflow
Solution 4 - Jqueryreza.cse08View Answer on Stackoverflow
Solution 5 - JqueryCD..View Answer on Stackoverflow
Solution 6 - JquerydrolexView Answer on Stackoverflow
Solution 7 - JqueryShriView Answer on Stackoverflow
Solution 8 - JqueryrichsageView Answer on Stackoverflow
Solution 9 - Jquerydanchoif2View Answer on Stackoverflow
Solution 10 - JquerybenrwbView Answer on Stackoverflow
Solution 11 - JquerySimon EastView Answer on Stackoverflow
Solution 12 - JqueryCarlo RoosenView Answer on Stackoverflow
Solution 13 - JqueryDSblizzardView Answer on Stackoverflow
Solution 14 - JqueryNoriView Answer on Stackoverflow
Solution 15 - JquerysuperheroView Answer on Stackoverflow
Solution 16 - Jqueryuser1018494View Answer on Stackoverflow
Solution 17 - JqueryDaveView Answer on Stackoverflow
Solution 18 - JqueryBrian M. HuntView Answer on Stackoverflow
Solution 19 - JqueryLodewijkView Answer on Stackoverflow
Solution 20 - JqueryProstil HardiView Answer on Stackoverflow
Solution 21 - JqueryBarry FranklinView Answer on Stackoverflow
Solution 22 - JqueryPablo WerlangView Answer on Stackoverflow
Solution 23 - JqueryKatya DolgovView Answer on Stackoverflow
Solution 24 - Jquerysamb102View Answer on Stackoverflow
Solution 25 - JqueryTrevor MeierView Answer on Stackoverflow
Solution 26 - Jquerynanachi1View Answer on Stackoverflow
Solution 27 - JqueryAlphaxard NgangaView Answer on Stackoverflow
Solution 28 - Jquerydavidman77View Answer on Stackoverflow
Solution 29 - JqueryrotaerczView Answer on Stackoverflow
Solution 30 - JquerytimView Answer on Stackoverflow
Solution 31 - Jqueryelano7View Answer on Stackoverflow
Solution 32 - JqueryPhilipp PoropatView Answer on Stackoverflow