Mithun Sreedharan
Mithun Sreedharan

Reputation: 51272

How to find whether text in a text area is wrapped to multiple lines?

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?

Upvotes: 3

Views: 4545

Answers (1)

techfoobar
techfoobar

Reputation: 66663

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;
}

Upvotes: 5

Related Questions