Autogrow Textarea Plugin Version 2.0

[red_box]Check out the newer version of this plugin![/red_box]
Today, I am glad to announce a new version of the Autogrow Textarea plugin. There were quite a few people that submitted feedback and I tried to take all that into consideration. Your comments are still welcome.

The plugin can be tried on this textarea:

It may not be apparent, but there are a quite a few things that have changed with this new version. Here’s the list:

  • It automatically resizes your textarea; before you had an algorithm that calculated the correct width according to your font-size and cols settings. Now, the plugin does it automatically. Big time saver.
  • It automatically sets the correct CSS attributes; before the user had to enter this manually in the CSS file. Now it’s done by the plugin.
  • The plugin is fired when the page loads; a lot of users requested this feature. When you load a page with data already entered in the textarea, the latter will automatically resize itself.
  • The plugin fires on more events; the plugin used to be fired when the user was typing. Now it does more than that.
  • It no more pollutes the global namespace; if you’re not familiar with these terms, let’s just say the code will not conflict with other Javascripts.

You may have guessed it. The setup is now much faster. You simply download the plugin : jquery.autogrowtextarea.js and call the Javascript method. The code is :

<script type="text/javascript">
  $(document).ready(function(){
    $("#txtInput").autoGrow();
  });
</script>
<textarea id="txtInput" cols="40" rows="5"></textarea>

There you go. Enjoy! And do leave your feedback, please.

Licensing

A lot of people have been emailing/commenting asking about Autogrow Textarea’s licensing. I finally decided I to go with this one : Beerware License.


[red_box]Check out the newer version of this plugin![/red_box]

101 Comments to “Autogrow Textarea Plugin Version 2.0”

  1. Adriana says:

    Sexy stuff. I love codes.

  2. Javier says:

    Hi Jevin,

    I spent the whole afternoon looking for a clean solution to this and all I saw before your post were spastic on-off scrollbars or extra lines to avoid that. (Though yours has an extra line of text, I lowered that value to fit exactly with the text lines and It goes on working smoothly as silk).

    Great work & thanks for sharing it!

    Javier

  3. Jevin says:

    @Javier

    Thanks for the comment. ;-)
    The extra line is there for browser compatibility. Glad you could easily remove it.

  4. Alex Ilyin says:

    There is a bug: Try to copy first paragraph of this post 10 times into text area – several words will get out of view (in Firefox).

  5. Jevin says:

    @Alex

    You are right. I’ll have to check on that. The thing is, the plugin counts the number of characters and derives the number of lines needed. With wrapping and all that, the calculation becomes more complex.

    I’ll try to find a solution for that though. If you have suggestions, do let me know. ;-)

  6. Carney L says:

    Jevin,

    Thanks for this plugin. In our use case, we have a textbox that is width:100%. So, if we resize the browser window, the width/character count calculations are thrown off so that way more rows get added to the textbox than are needed. Any idea how we might address this?

  7. Carney L says:

    Also, this thread might help solve the problem, but i’m no javascript expert :/

    http://stackoverflow.com/questions/931207/is-there-a-jquery-autogrow-plugin-for-text-fields

  8. Jevin says:

    @Carney

    You are right the calculations will not work in your case. Unfortunately, you will not be able to use the plugin in your case. I am, in parallel, trying to figure out another algorithm that would achieve the same goal. If ever I find something, I’ll let you know on the blog.

  9. Jeff says:

    Wow! Doesn’t work in IE 8 (Windoze) or FF 3 (linux). Looks good in FF 4, not needed in Opera or Chrome. The one sucky browser that is still used my all the people that don’t know better – and it doesn’t work. Guess I’ll have to keep looking while you fix this.

  10. Jevin says:

    @Jeff,

    I haven’t tested it on IE8. I’ll have to check on that. It must be because of some incompatible Javascript.

  11. Bangon Kali says:

    How did you remove the extra line? I’m planning to have a one line default number of rows. Can’t seem to get through it. :(

  12. Bangon Kali says:

    Lol! My bad! Found it! xD I’m really sorry for posting out immediately without looking at the code. Thanks though! This is a very helpful code! Thank you very much! :D

  13. Nicholas Morgan says:

    My only problem with this is that I use CSS to define the width and height of my textarea. Yours uses HTML cols and rows attributes of the textarea element which screws up the size that I want for my textarea. Would you know of a way to fix this? Regardless it is a cool plugin and of course I thank you for your work and willingness to contribute.

  14. Jevin says:

    @Nicholas

    Actually, the whole calculation is based on the number you specify in your cols attribute. So if you use CSS, the calculation would be all wrong.
    I totally get you, but there is no other way round.

  15. mike says:

    I can’t seem to make this work on a class. Should it work, or do I have to use an id? $(‘.autogrow’).autoGrow();

  16. camden_kid says:

    Excellent.

    This is easily the best autogrower I have come across after much searching.

    Keep up the good work.

  17. beuzbizouille says:

    great code, thank you ! =)

  18. Ole Marius Løset says:

    Firefox’ rendering of textarea is buggy, it renders +1 rows more than defined, so whenever it’s rows=”1″ it’ll be rendered as rows=”2″. Works if styled via CSS – height:16px;

  19. Lambert Guevarra says:

    @Ole Marius

    I also experience this kind bug on FF. Not just the row but it also have an uncontrollable width behavior

  20. Paul says:

    Poorly documented… doesn’t work from the pseudo example for me. Writing good code blah, blah, blah… is also making a clear simple distinct example that covers no more than the essentials. The box shows but the dots in corner don’t? Probably something simple but why are you wasting my time with your arrogance? Provide a clear, simple, complete example!

  21. Nelson says:

    I hope to make an auto-growing textarea with the fixed width but not cols. Do you have any ideas?

  22. Jevin says:

    @Paul

    I am with you about the documentation thing. But, this plugin is so easy to use. It’s just 2 lines of code. ;-)

    If the example is not working for you, it might be because you don’t have Javascript activated. What browser are you using?

    @Nelson

    That’s a nice idea. I don’t have any advice to give you other than taking my plugin and modifying it. ;-)

  23. Tom says:

    Hi,

    Great stuff! Thanks!

    I’ve made 1 adjustment:
    at the end, when you add event listeners, I think it’s better to unbind the old ones if they exist, e.g.:

    $(this).unbind(‘keyup focus blur’, grow).bind(‘keyup focus blur’, grow);

    Thanks,
    Tom

  24. Scott says:

    Great plugin! So clean and easy to use.

    However, I’m using it primarily for a mobile site I’m working on and am having problems with BB 6.0′s browser. It’s making it a small sliver in width and isn’t autogrowing at all.

    Also, as to getting it to work with % widths, I’ve done the following before calling .autoGrow() :

    find the width of one col (which was done by alerting the width with 20 & 21 cols and finding the difference… mine was 6px and my textarea has 4px padding)

    $(“#textareaID”).attr(“cols”, ($(“#textareaID”).width() – 8) / 6);

    It’s a wee bit messy and you have to recheck it when changing font sizes but it makes it work.

  25. ric says:

    hi
    has anyone tested this plugin on elements with the display property set to hidden?
    i am getting very high textareas, way beyond it’s containing text when i set the autogrow to a textarea that is in a div that is hidden with display.

    i don’t have time to pin point the bug right now, so i’m just gonna throw it out there for you guys.

    regards

  26. Guillermo says:

    Hi, it doesn’t work if I add items programmatically, Is there any way I can make it work?
    Thanks!

  27. Mike says:

    Hey, I really like your plugin. However, I’m having issues with Firefox 5, and 6. It displays very differently compared to other browsers (Chrome/IE). The overall width is much greater and the auto-height is displaying two rows instead of the one that I specify. Any thoughts.

    Thanks.

    • Jevin says:

      The extra rows are normal. They cater for browser incompatibilities.
      As for the width problem, I can’t seem to reproduce that on my Firefox 6.0. You should try in on another PC using the same version of FF, just to make sure it’s not to do with your PC.

  28. Andrew says:

    Very nice plugin, clean, simple, and easy to use, but I am running into a small problem/issue (?) with it…

    We have a page with multiple TeaxtAreas, which may be pre-populated from a database. We are using a JavaScript function (“ismaxlength()” courtesy of DynamicDrive.com) to limit the amount of text that could be typed into the box. This works fine, but when I add your plugin to the page, this limiting function is being ignored.

    Is there something than needs to be done to get these two to play nice with each other?

  29. Anthony says:

    Great plugin, but it’s having issues working inside of a div that I’m hiding via display: none , then switching to display: inline, can only get my textarea to be 1col wide. Any ideas?

  30. Anthony says:

    Get my message?

  31. Andrei says:

    Repo available (GitHub, BitBcket, etc.)? Would be much more convinient.

  32. Randy Harding says:

    I am trying to replace the textbox with the textarea. As a newbee to web development I cannot figure out how to bind the text area to the sqldatasource. The text=” that I used in the textbox does not seem to work in textarea.

    What am I not understanding?

  33. I think most people run into issues when they don’t use the jQuery noConflict in their code (mainly a fault of nearly every jQuery writer). Try the text below if your having any issues.

    jQuery.noConflict();

    jQuery(document).ready(function(){
    jQuery(“#txtInput”).autoGrow();
    });

  34. Steve says:

    So how do I get Autogrow to start with just 1 line? Setting the row to 1 does not seem to do it.

  35. Frank says:

    This script still active? It doesn’t look like the author has much time for support…

    • Jevin says:

      Yep the plugin is still active.

      As for the support, with my daily work and stuff, I can’t reply to each and everyone. So I just pop in when there is a major need.

  36. Nathan says:

    In works fine on Chrome for Mac. However in Chrome for Windows I get “Uncaught TypeError: Object [object Object] has no method ‘autoGrow’”.

  37. Nathan says:

    Actually, at line line of the script it says:
    Uncaught SyntaxError: Unexpected end of input

  38. Frank says:

    Hmm…. I guess it’s off to find something else. Too bad…

  39. Frank says:

    Not so much support but I don’t want to implement something that is not being maintained. There are a number of requests to have the ability to have the input start with 1 row and would be great to get feedback from the author on it.

  40. Frank says:

    What would be ideal is starting with one line and when active, it adds a second line to ensure users they still have room to type.

    • Jevin says:

      Hmmm, did you try setting rows attribute to 1 in your textarea? That should do it.

      The plugin is maintained. I don’t do frequent releases because, simply, there are no major bugs. And that’s because, deep down, the plugin is pretty straightforward.

  41. John Eckman says:

    What license is this released under?

    I generally assume JQuery plugins are dual MIT/GPL, like JQuery, but it would better if you indicated that here somewhere.

    Right now there’s just a copyright statement.

    Thanks!

  42. Frank says:

    I did try the attribute setting to 1 and it did not work.

  43. Vasche says:

    One-liner doesn’t work. After I modified the code to this:

    if (linesCount > rowsDefault)
    obj.rows = linesCount;
    else
    obj.rows = rowsDefault;

    I now see the text scrolling before control is resized.

  44. Vasche says:

    Also, I use proportional font, that makes the math faulty.

  45. Vasche says:

    And one more thing: Please consider building in the autosubmit feature on Enter, and newline on Shift+Enter

  46. ulumuddin says:

    how if i use class tag for textarea ?

    this seems couldn’t work

    *sorry for my bad english

  47. Guys,

    When you think about it, it’s not too difficult to have this plugin use your width defined in your inline style or stylesheet for the textarea. Jevin has already done the heavy lifting by getting the character width for you. Now all you have to do is divide your intended width by the character or column width and now you have your new column count. This is also perfect cross browser because as I was testing I was able to adjust this and have it just about perfect in FF to see that in IE it was WAY off. So I had to fix this.

    See below…

    /*!
    * Autogrow Textarea Plugin Version v2.0
    * http://www.technoreply.com/autogrow-textarea-plugin-version-2-0
    *
    * Copyright 2011, Jevin O. Sewaruth
    *
    * Date: March 13, 2011
    */
    jQuery.fn.autoGrow = function(){
    return this.each(function(){
    // Variables
    var colsDefault = this.cols;
    var rowsDefault = this.rows;
    var intendedWidth = parseInt($(this).css(‘width’)); // REMOVE ‘px’
    this.style.width = “auto”; // Set to auto or the characterWidth function does not work

    var characterWidth = function (obj){
    var characterWidth = 0;
    var temp1 = 0;
    var temp2 = 0;
    var tempCols = obj.cols;

    obj.cols = 1;
    temp1 = obj.offsetWidth;
    obj.cols = 2;
    temp2 = obj.offsetWidth;
    characterWidth = temp2 – temp1;
    obj.cols = tempCols;

    return characterWidth;
    }

    var charWidth = characterWidth(this);
    var adjustedWidth = ((charWidth * this.cols) + 6); // The width the script was initially adding
    var newCols = Math.floor(intendedWidth / charWidth); // The new number of cols
    var newWidth = newCols * charWidth; // New width based on max cols found above

    colsDefault = newCols; // Reset colsDefault

    //Functions
    var grow = function() {
    growByRef(this);
    }

    var growByRef = function(obj) {
    var linesCount = 0;
    var lines = obj.value.split(‘\n’);

    for (var i=lines.length-1; i>=0; –i)
    {
    linesCount += Math.floor((lines[i].length / colsDefault) + 1);
    }

    if (linesCount >= rowsDefault)
    obj.rows = linesCount + 1;
    else
    obj.rows = rowsDefault;
    }

    // Manipulations
    this.style.width = “auto”;
    this.style.height = “auto”;
    this.style.overflow = “hidden”;
    this.style.width = newWidth + “px”; // Set to our new found max cols width
    this.onkeyup = grow;
    this.onfocus = grow;
    this.onblur = grow;
    growByRef(this);

    });
    };

  48. Stan Quinn says:

    Great plugin…definitely saved me some time. I had a problem in IE9 for a bit. It thought I was missing a “}”. Modified the code from
    if (linesCount > rowsDefault){
    obj.rows = linesCount + 1;
    else
    obj.rows = rowsDefault;
    to
    if (linesCount > rowsDefault){
    obj.rows = linesCount + 1;
    }

    else {
    obj.rows = rowsDefault;
    }
    and it seemed to fix the problem. (Shouldn’t…but that’s IE for ya) I also hacked a few lines to create fixed width and no resize icon and single line…although it tends to create a new line early and maintain the double line thereafter. It’s in my facebook app: http://apps.facebook.com/mytopslist/ ….the code’s been minified, but i have a development version of my version of the plugin js code at http://www.webmasterninjas.com/facebook/mytops/inc/js/jquery.autogrowtextarea.mytops.js….Oh, and your comment captcha kinda sucks….didn’t work the first few times

  49. Jessy Jas says:

    Hi,
    Can I use it free or need to buy this plugin.
    Please tell me. This is nice plugin for textareas and it is very simple.
    I am glad if this is free. Pl. tell me…

    Thanks in advance.

  50. Eugo says:

    I have pages with up to 200 textareas, most of them initially invisible, and there was a problem when your code would leave them with cols=”1″ when they contained no text. So I tweaked the code a bit:
    // binding
    this.onkeyup = grow;
    this.onfocus = grow;
    this.onblur = grow;
    // Manipulations
    this.style.width = “auto”;
    this.style.height = “auto”;
    this.style.overflow = “hidden”;
    if ($(this).val()) {
    this.style.width = ((characterWidth(this) * this.cols) + 6) + “px”;
    growByRef(this);
    }
    });

    And then this works perfectly – tried in FF7, IE8, Chromium (doesn’t report version). Much easier and faster than Padolsey’s, which relies on a ghost clone of the textarea, which then needs to have several properties specially set, height 0, then scrolls 10000 and tries to get .scrollTop() – which turned out rather unreliable in my setting. I’ve had IE return random numbers, textarea growing and shrinking by a line every time I touch a key (even arrows) etc. With 250 textareas, it would take 45 seconds to do them all – same page now renders in 6 seconds.

    This works :)

  51. Devin says:

    I’m looking for a callback function when the textarea resizes so I can resize other things on the page – any ideas?

    Thanks!
    - Devin

  52. Tom says:

    This is a great script. However in my case my textareas need to be set to 100% of the browser width so the cols attrib doesn’t work for me. Can you suggest a way to get around it?

  53. Alex says:

    If i use Firefox and resize the textarea by hand (smal icon in the bottom right in the textarea, a Firefox inbuild feature) the textarea wont grow any more if i enter text :(

  54. Prabhu says:

    What licence under which this plugin come in? Is it MIT?

  55. Pilou says:

    Should calculate cols if they aren’t set from width.

    It would be good for Tom too.

  56. Jason says:

    Having probelms getting this to work. First I simply copied the code exactly. I’m guessing that there’s got to be more to this. Do I have to put a ‘script src=’ in the head? When running this through firefox, the error console gives me a
    “jQuery is not defined” in the jquery.autogrowtextarea.js and a ”
    $ is not defined” in my php page. What am I missing? Thanks.

    • Jason says:

      Wow. As soon as I hit the ‘post’ on this, I figured it out. I (as a newb) never called jquery to begin with. Just thought (foolishly) what you gave as code was all I needed. I learned something today and I thank you for that.

  57. Aen Tan says:

    The expansion isn’t happening only at line breaks. It grows at any point of the line which makes it slightly ‘imperfect’. Do you have a fix?

  58. Marc says:

    Does it HAVE to be a minimum of 2 rows? I’m trying to create a single line textarea but it automatically sets it to a minimum of 2 rows.

  59. Mzoe says:

    I want to add top margin to my send button whenever textarea expands, so it will keep send button aliging middle to it, I have tried everything but its not working for me, could you please help me out with this, here is the script:
    jQuery.fn.autoGrow = function(){

    return this.each(function(){
    // Variables
    var colsDefault = this.cols;
    var rowsDefault = this.rows;
    var addmargin = 0;

    //Functions
    var addmargintop = function () {
    addmargin = addmargin + 5;
    $(‘#sendMessageButton’).css(“margin-top”,addmargin);
    }
    var grow = function() {
    growByRef(this);
    addmargintop();
    }

    var growByRef = function(obj) {
    var linesCount = 0;
    var lines = obj.value.split(‘\n’);

    for (var i=lines.length-1; i>=0; –i)
    {
    linesCount += Math.floor((lines[i].length / colsDefault) + 1);

    }

    if (linesCount >= rowsDefault)
    obj.rows = linesCount + 1;

    else{
    obj.rows = rowsDefault;}

    }

    var characterWidth = function (obj){
    var characterWidth = 0;
    var temp1 = 0;
    var temp2 = 0;
    var tempCols = obj.cols;

    obj.cols = 1;
    temp1 = obj.offsetWidth;
    obj.cols = 2;
    temp2 = obj.offsetWidth;
    characterWidth = temp2 – temp1;
    obj.cols = tempCols;

    return characterWidth;

    }

    // Manipulations
    this.style.width = “auto”;
    this.style.height = “18px”;
    this.style.overflow = “hidden”;
    this.style.width = “70%”;
    this.onkeyup = grow;
    this.onfocus = grow;
    this.onblur = grow;
    growByRef(this);

    });

    };

  60. Bassmo says:

    Just a thought, why not position the button relative to the bottom of the container? (Make the container position relative and the submit button position absolute, located by bottom and left) – not tested it but might work :)

  61. Bassmo says:

    (having it in the middle of the text box a bit weird if the text box gets very big)

  62. Vilius says:

    Autogrow textarea is exactly that my client wanted. Perfect, thank You!

  63. Femke says:

    Hi thanks for making this, some questions though..
    Can I set the initial width and height someway? Best would be in px in the css.. I want the box to look like a input field, so one row.. is this possible? How would you do this?

    • Femke says:

      Sorry, got it already >.<
      For others, you can use some jquery after the .autoGrow().
      $("#txtInput").css('width','500px');

  64. kourosh says:

    great. it works but needed some width modification to have it tailored. thanks

  65. kourosh says:

    When I put the whole script at the end of my document just before the , it doesn’t work! when I have the script loaded on top of document, it works? what is the explanation? thanks

  66. Obiez says:

    It was a great post. I really appreciate that. But how do i control the “textarea” element will grow only when the user had pressed combination key (SHIFT + Enter).

    this is the code, but still not working :

    $(document).ready(function() {
    $(“.autogrow_textarea”).bind(‘keypress’, function(event) {
    if( event.which === 13 && event.shiftKey ) {
    alert(‘you pressed SHIFT+Enter on this textarea’);
    $(“.autogrow_textarea”).autoGrow();
    }
    });
    });

    Thanks

  67. Oxo says:

    Thanks, I will drink a beer in your honor ;-)

  68. Cupidvogel says:

    This doesn’t work properly. Keep pressing down the Enter key, and you will see the scrollbar with the scrollsize decreasing furiously. Only when you release the button does the scrollbar again disappears.

  69. Denis says:

    Hi,
    Great pluggin.
    Would be awesome if we didn’t have to set a cols on the textarea. Can it be set automatically?
    My textareas are in percentage width (ie 95%) and change depending on window size.

    Thanks for the help.

  70. Travis says:

    I’m not sure why, but I kept getting an error from you file. It seems that somehow all the code was being interpreted as one line, so everything past the first comment was commented out.

    Maybe it is an encoding issue?

    This is weird, considering no one else seems to be having any problems. Anyway, I fixed the problem by running the code through http://jscompress.com/

    Otherwise, thanks for the nice script.

  71. Amit says:

    This is what i was looking for, I just need to “Enter” key support, on enter key i want to post the data to next form.

Leave a reply