3

How can I find whether a long text in a textarea is wrapped into two or more lines?

I'm not talking about the new line chars as discussed here.

I'm aware of the plugin Textarea Line Count

Any simpler method?

Community
  • 1
  • 1
Mithun Sreedharan
  • 49,883
  • 70
  • 181
  • 236
  • 5
    As far as simplicity of use, I don't think you are going to be able to find a simpler solution than the plugin you linked. Since line wrapping is based on the size of the textarea, you'd almost certainly have to calculate the maximum number of characters a line could contain based on width of the textarea and width of the font, then make some sort of calculation. Non-monospace fonts complicate this further. What do you consider simpler than the Textarea Line Count plugin? – crush Apr 05 '13 at 13:38
  • 1
    I considered creating a temporary div with the same styling and measuring the height of that, but due to browser differences this isn't exact. Not sure if it would be worth the trouble. For more details, see: http://stackoverflow.com/a/3697221/1306809 – Matt Coughlin Apr 05 '13 at 14:51

1 Answers1

5

I experimented on this and came up with a hack that involves the following:

  1. Disabling text-wrapping in the textarea (plus disable padding)

  2. Checking if the textarea's scrollWidth is greater than it's width.

The basic logic i used was that if the text is spanning multiple lines, that means when wrapping is turned off, we should get a horizontal scrollbar.

Demo: http://jsfiddle.net/fnG3d/

Disclaimer: The code below is the result of a 10 minute fiddle, definitely not production quality

function checkMulti(id) {
    var ta = $('#'+id), multi = false;

    // disable wrapping, padding and enable horiz scoll
    ta.addClass('nowrap');

    // check if there is anything to be scrolled horizontally (means multi-lines otherwise)
    multi = ( ta[0].scrollWidth > ta.width() );

    // checking done. remove the class.
    ta.removeClass('nowrap');

    alert('Spread over multiple-lines: ' + multi);
}

/* the nowrap class */
.nowrap {
    overflow-x: scroll;
    white-space: nowrap;
    padding: 0;
}
techfoobar
  • 65,616
  • 14
  • 114
  • 135