Test if cursor is on the first line in a textarea (with soft-newlines)

Viewed 1979

Given a textarea with content that flows like this

     ––––––––––––––––––––––––––
    | This is some text, which |
    | wraps like this.         |
     ––––––––––––––––––––––––––

How can one tell if the text-cursor is on the first line of the textarea?

Obviously, checking for a newline character (\n) works if one wants to see if the cursor appears before the first line break, but testing for a 'soft' line break seems more challenging.

Here is a sample jsFiddle to experiment with.

I have not yet come up with a strategy, but I suspect it may involve copying the text up until the cursor position into a cloned textarea (or div), and making the width as long as it needs to be so it doesn't wrap. If the cloned area has a width less than the original's width, then the cursor would seem to have to be on the first line. There may a simpler option, something more elegant, or (best of all) an existing and well-tested solution.

Target browsers are Webkit (Chrome/Safari) & Firefox. I.e. IE compatibility is not a concern at this time (if that makes any difference).

Thanks for reading.

EDIT: Seeking line number of text caret, not mouse cursor.

falsarella gave an excellent answer, that highlighted an ambiguity in the question. What I am seeking is whether the text cursor (“caret” may be a better word) is on the first line. I have updated the question and the jsFiddle to reflect.

2 Answers
Related