Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextArea element - default size to fit content

Tags:

html

jquery

css

If I set a fixed width on a textarea element is there an elegant way of setting the height default to a size that would allow all it's content to fit?

I was hoping to avoid hard-coding anything in jquery that would compare text.length and try to equate a value to a height, but maybe that is the only way, i'd love to see some native css rule if possible but I can't seem to think of any off the top of my head.

I've created a fiddle illustrating what I am trying to accomplish. http://jsfiddle.net/edZgm/

here's the code:

CSS:

textarea {
    overflow: hidden;
}

JQuery:

$('document').ready(function () {
    $('textarea')
        .width(500);

    //I have a width set, but see how the height defaults to a rediculously small amount.
    //I'd like to have the height default to fit everything on load.

});

HTML:

<textarea> ... lots of text </textarea>

Thank you in advance.

like image 373
Dylan Hayes Avatar asked Apr 11 '13 17:04

Dylan Hayes


2 Answers

Making the comment an answer for future reference:

Checkout jquery-autogrow

like image 61
karthikr Avatar answered Sep 22 '22 20:09

karthikr


There is this jQuery plugin, Autosize.
http://www.jacklmoore.com/autosize/

Here is your fiddle updated with that plugin.
http://jsfiddle.net/edZgm/3/

Just loaded the plugin and added this to your code.

    $('textarea')
    .autosize();
like image 21
Arbel Avatar answered Sep 23 '22 20:09

Arbel