Reputation: 5315
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.
Upvotes: 135
Views: 194621
Reputation: 130195
This requires Chrome version 123
minimum and is using field-sizing
property
textarea {
field-sizing: content;
width: 200px;
}
<textarea>
Here is a
Multiline
Textarea
</textarea>
Below 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)
$(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 rows, minRows = this.getAttribute('data-min-rows') | 0;
this.rows = minRows
rows = Math.floor((this.scrollHeight - this.baseScrollHeight) / 16)
this.rows = minRows + rows
});
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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<textarea class='autoExpand' rows='3' data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>
Upvotes: 34
Reputation: 141
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);
}
Upvotes: 0
Reputation: 2721
Try this:
$('textarea[name="mytextarea"]').on('input', function(){
$(this).height('auto').height($(this).prop('scrollHeight') + 'px');
});
Upvotes: 3
Reputation: 6178
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>
Upvotes: 27
Reputation: 65
this worked for me perfectly well
$(".textarea").on("keyup input", function(){
$(this).css('height', 'auto').css('height', this.scrollHeight+
(this.offsetHeight - this.clientHeight));
});
Upvotes: 2
Reputation: 2255
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.
Upvotes: 0
Reputation: 11
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.
Upvotes: 1
Reputation: 81
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>
Upvotes: 1
Reputation: 1114
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/
Upvotes: 1
Reputation: 3758
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/
Upvotes: 0
Reputation: 11
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);
});
});
});
Upvotes: 1
Reputation: 6482
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..
Upvotes: 2
Reputation: 121
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>
Upvotes: 3
Reputation: 22570
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
Upvotes: 170
Reputation: 399
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/
Upvotes: 1
Reputation: 1820
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.
Upvotes: 1
Reputation: 391
@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
Upvotes: 0
Reputation: 2630
To define a auto expandable textarea, you have to do two things:
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.
Upvotes: 10
Reputation: 65264
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.
Upvotes: 117
Reputation: 883
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)
Upvotes: 4
Reputation: 61
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.
Upvotes: 1
Reputation: 3971
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';
}
});
Upvotes: 1
Reputation: 83818
There is also the very cool bgrins/ExpandingTextareas (github)
project, based on a publication by Neill Jenkins called Expanding Text Areas Made Elegant
Upvotes: 1
Reputation: 4149
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;
};
}
});
Upvotes: 3
Reputation: 5521
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; }
Upvotes: 11
Reputation: 83
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 Searching for the Ultimate Resizing Textarea for more information.
Upvotes: 1
Reputation: 41
Everyone should try this jQuery plugin: xautoresize-jquery. It's really good and should solve your problem.
Upvotes: 4
Reputation: 1045
I fixed a few bugs in the answer provided by Reigel (the accepted answer):
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 , 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, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n/g, '<br/>')
.replace(/\s/g,' ');
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));
Upvotes: 3
Reputation: 58490
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 this bug which returns the incorrect value for scrollHeight
, so the above code contains a (hacky) workaround for it.
Upvotes: 3