0

I wrote a little jquery to resize my text area as you type, and it works fine unless I use a line break.

function resize() {
    var value = $('textarea').val();
    var div = $('div');
    div.html(value);

    var height = div.height();
    /// etc. 
}

<div style="display: none;"></div>
<textarea></textarea>

The text area and div have the same font and everything, so they align perfectly and the text area resizes accordingly, but when I use a line break (example: "one<br />two") the output to the div ignores it ("one two"). How do I make it include the line break?

user2250471
  • 1,002
  • 3
  • 10
  • 23
  • 2
    If the CSS matches exactly, then try adding `white-space:pre;` –  Jun 14 '14 at 14:15
  • Instead of using `div.html()`, you can try `pre.text()` – billc.cn Jun 14 '14 at 14:15
  • Duplicate? Here: http://stackoverflow.com/questions/10950538/how-to-detect-line-breaks-in-a-text-area-input or here: http://stackoverflow.com/questions/19581393/html-textarea-input-doesnt-recognize-line-breaks – Mark Jun 14 '14 at 14:15
  • @Mark Of the second, yes. The first is about counting, though. I am glad I never read those answers when I built this for myself. Much easier ways exist. :) –  Jun 14 '14 at 14:18

1 Answers1

1

See my fiddle with complete code: http://jsfiddle.net/billccn/8kgpc/1/. Two tricks I used:

  • Use a <pre> so the linebreak is preserved
  • Add a new line during the measurement so that there's always extra space in the textarea

The core code is simple:

$(this).height($('pre').text(this.value + '\na').height());

In the fiddle, I've changed the text size to show it still work in that case.

billc.cn
  • 7,187
  • 3
  • 39
  • 79