Skip to content

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]

Published inCoding
  • Adriana

    Sexy stuff. I love codes.

  • Javier

    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

  • @Javier

    Thanks for the comment. ๐Ÿ˜‰
    The extra line is there for browser compatibility. Glad you could easily remove it.

  • Alex Ilyin

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

  • @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. ๐Ÿ˜‰

  • Carney L

    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?

  • Carney L

    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

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

  • Jeff

    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.

  • @Jeff,

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

  • Bangon Kali

    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. ๐Ÿ™

  • Bangon Kali

    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! ๐Ÿ˜€

  • Nicholas Morgan

    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.

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

  • mike

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

  • camden_kid

    Excellent.

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

    Keep up the good work.

  • beuzbizouille

    great code, thank you ! =)

  • Ole Marius Lรธset

    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;

  • Lambert Guevarra

    @Ole Marius

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

  • Paul

    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!

    • Douchhater lol

      Wow, what a douche

      • Josh

        Yea example worked for me…maybe he doesn’t get it?

  • Nelson

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

  • @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. ๐Ÿ˜‰

  • Tom

    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

    • Not essential, but additional safety is always a good thing.

  • Scott

    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.

    • Scott

      ugh, the – 8) is – 8 )

    • Hmmm, the plugin already calculates the exact size of one character and then re sizes the textarea accordingly. Did you notice any difference when you added your code?

  • ric

    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

    • Strange behavior. What exactly do you mean by “i am getting very high textareas”?

      • I’m getting the same bug. When autoGrow() is called on a hidden element (display: none) it’s width becomes really tiny. Any idea how to solve this?

  • Guillermo

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

    • Have you tried calling $(“#txtInput”).autoGrow(); again?

  • Mike

    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.

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

  • Andrew

    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?

    • Hello,
      Clearly, both plugins are conflicting with each other. Can you send me the code inside “ismaxlength()”? I’ll see if I can fix something for you.

      • Andrew

        Jevin, as stated we are using the JavaScript located here to limit the TextArea size: http://www.dynamicdrive.com/dynamicindex16/maxlength.htm

        Due to the ‘hiccup’ with your plugin, we went with another plugin, but I hope you are able to fix whatever may be at the root of this issue.

        Thanks

        — Andrew

  • Anthony

    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?

    • You’re the second person having the same issue. Can you send me a link where I can see how you’re using the plugin?

      • Anthony

        I’ll contact you directly via your contact form.

      • Alan

        I’m also having this issue, was there a resolution for it?

  • Anthony

    Get my message?

  • Andrei

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

  • Randy Harding

    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?

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

  • Steve

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

  • Frank

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

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

  • Nathan

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

  • Nathan

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

    • Do you have any link where I can see the said bug?

      • Nathan

        I found the issue. The end-of-line character was MAC. I changed it to UNIX and it fixed it. I’m not sure if the problem is at the source or if something I did did that.

  • Frank

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

    • Out of curiosity, what kind of support where you after?

  • Frank

    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.

  • Frank

    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.

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

  • 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!

  • Frank

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

  • Vasche

    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.

  • Vasche

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

  • Vasche

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

    • Hey, thanks a lot for the suggestions. I’ll see what can be done.

  • how if i use class tag for textarea ?

    this seems couldn’t work

    *sorry for my bad english

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

    });
    };

  • 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

  • Jessy Jas

    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.

  • fdbdf

    dfbdb

  • Eugo

    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 ๐Ÿ™‚

  • Devin

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

    Thanks!
    – Devin

    • Well, you can call your other functions right after the “$(‘#txtInput’).autoGrow();” line.

  • Tom

    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?

  • Alex

    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 ๐Ÿ™

    • Jeff

      Try setting the css resize style on the textarea to none. e.g. style=”resize: none”

  • Prabhu

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

  • Pilou

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

    It would be good for Tom too.

  • Jason

    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

      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.

  • 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?

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

  • Mzoe

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

    });

    };

  • Bassmo

    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 ๐Ÿ™‚

  • Bassmo

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

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

  • Femke

    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

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

  • kourosh

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

  • kourosh

    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

  • Obiez

    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

  • Oxo

    Thanks, I will drink a beer in your honor ๐Ÿ˜‰

  • Cupidvogel

    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.

  • Denis

    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.

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

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

  • Pingback: Bingo – All Purpose Responsive Admin Template | themesafe()

  • Pingback: Star Themes | Bingo – All Purpose Responsive Admin Template()

  • Pingback: Bingo - All Purpose Responsive Admin Template | 9Downloads()

  • Pingback: Bingo – All Purpose Responsive Admin Template | Scripts CodeCanyon()

  • Pingback: Bingo – All Purpose Responsive Admin Template | HTML5 | Admin Templates()

  • Pingback: Nulled Free Bingo - All Purpose Responsive Admin Template Download()

  • Pingback: Bingo — All Purpose Responsive Admin Template — Site Templates — Nulled()

  • Pingback: Download Bingo – All Purpose Responsive Admin Template()

  • Pingback: Autogrow Textarea Plugin Version 2.0 - Pixel Library()

  • Pingback: Bingo - All Purpose Responsive Admin Template - BestWpThemes()

  • Pingback: Bingo - All Purpose Responsive Admin Template - Theme for Club()

  • Pingback: Bingo – All Purpose Responsive Admin Template Free Download Themeforest – BladeZee()

  • Pingback: Bingo - All Purpose Responsive Admin Template - Traclaborat()

  • Pingback: Bingo - All Purpose Responsive Admin Template - Theme For u()

  • Pingback: Bingo - All Purpose Responsive Admin Template -()

  • Pingback: Bingo - All Purpose Responsive Admin Template()

  • Pingback: Download Free Bingo - All Purpose Responsive Admin Template()