2

I have a textarea that has a set css height of 85px. A user might type lines of content within that textarea, and I would like to know how high the text/val is, NOT the text area itself.

Is there a way to check the height of the inside text including line breaks?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412
  • Why don't you take a look at this plugin - http://plugins.jquery.com/project/autogrowtextarea – Hari Pachuveetil May 13 '11 at 17:57
  • Try to count characters, since textarea has cols and lines attr, you can stimate the height based in the lines of the text. I don't have a clear answer for that. – Jepser Bernardino May 13 '11 at 17:57
  • To help guide answers in the right direction: WHY do you need to know the Height of the text? – drudge May 13 '11 at 18:01
  • You can check out [this answer](http://stackoverflow.com/questions/3341496/javascript-how-to-get-the-height-of-text-inside-of-a-textarea). – Dzung Nguyen May 13 '11 at 18:00

3 Answers3

1

I would duplicate the content of the textarea into another element with the same width, hidden, and then get its height.

jackJoe
  • 11,078
  • 8
  • 49
  • 64
1

This is how I'd do it, though obviously the mark-up is only generic and to be amended to your needs:

html

<div class="counter"></div>
<textarea></textarea>
<div class="tmp"></div>

CSS

textarea, div {
    width: 150px;
    resize: none;
    border: 1px solid #ccc;
    padding: 0;
    margin: 0;
    font-size: 1em;
    font-family: Arial, sans-serif;
}
textarea {
    height: 85px;
}
div {
    min-height: 85px;
}

jQuery:

$('textarea').keyup(
    function(e){
        var t = $(this).val();
        $(this).next('.tmp').text(t);
        $(this).prev('.counter').text('Height is: ' + $(this).next('.tmp').outerHeight());
    });

JS Fiddle demo.

This could be amended to dynamically add, and remove, the .tmp divs as required. But I was trying to keep this as simple as possible, so I left it hard-coded.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

I'm not sure exactly why you're wanting to do this. If you are just trying to have the box increase in size to match the text, use one of many extensions such as:

http://unwrongest.com/projects/elastic/

If this isn't what you're looking for, you can have a look at the source and see how they achieve this, and mimic it.

James Montagne
  • 77,516
  • 14
  • 110
  • 130