开发者

Auto expand a textarea using jQuery

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 textbo开发者_Go百科x when my agenda's text keep growing that textbox area.


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


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.


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;
    });


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>


  • Auto Growing Textareas
  • jQuery Autosize


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; }


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.


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


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


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)


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.


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));


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;
        };
    }
});


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>


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..


this worked for me perfectly well

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


Try this:

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


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");
}


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.


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


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'; 
    }
});


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.


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.


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/


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 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/


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>


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.


@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


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜