Showing posts with label css textarea jquery javascript. Show all posts
Showing posts with label css textarea jquery javascript. Show all posts

Friday, November 29, 2013

Setting textarea height adjusted to the contents

I have a page I would like to print out having <textarea> printed as well.
I would like to have this <textarea> having maximum width, and minimum height, so where there is no data it is only one line, but in case the data spans to, let's say, 10 rows, it expands <textarea> to 10 rows, and no scrollbar appears.

This is what I have found that works for me:

    $(".tarows").each(function(){
        $(this).height(0) ;
        $(this).height($(this).prop("scrollHeight") + "px") ;
     }) ;

- or similar using pure javascript:

    element.style.height=0;
    element.style.height=element.scrollHeight+'px';


This way, I can define my textarea (using class tarows) without cols or rows, and say in css to make it 100% width:

.tarows {
    width: 100%; 
}

<textarea class="tarows">multiline text which will be shown on the whole width of the page, and as many rows as needed.</textarea>