This is a JavaScript solution wrapped in perl which I did for a project a couple months ago. merlyn is quite right, of course, about XHTML being unpredictable in different browsers and user settings. I usually do percentage and em based layouts to try to compensate for this but there is no perfect solution.

You can transfer the "algorithm" to perl code pretty easily. It's just trying to get the text area somewhere between 3 and (update 42) 40 ems high and fit the text inside as well as possible. Takes into account character count and line breaks and tries to get a reasonable middle ground. You can play with it dynamically and salt the settings and CSS to taste.

use CGI qw(:standard); print header(), start_html(-title => 'Textarea madness!', -script=> <<'EndJS', function fixTextarea ( elemId ) { var box = document.getElementById(elemId); var height = Math.floor( box.value.length / 50 ); var newlines = box.value.match(/(\n)/g); if ( newlines ) height += Math.floor( newlines.length * .7 ) + 3; if ( height < 3 ) height = 3; if ( height > 40 ) height = 40; box.style.height = height + 'em'; } EndJS ), h2("Textarea with JavaScript assisted dynamic resize"), start_form(), textarea( -style => 'width:40em;line-height:120%;overflow:auto;', -id => 'response', -onfocus => "fixTextarea('response')", -onkeypress => "fixTextarea('response')", -name => 'response', ), script({-type=>'text/javascript'}, # call it up front "fixTextarea('response')" ), end_form();

In reply to Re: Estimating height of TEXTAREA from content by Your Mother
in thread Estimating height of TEXTAREA from content by tomazos

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.