Check if the cursor is in the first line in the text box (with soft newline characters)

Given a text box with content that flows this way

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

How to determine if a text cursor is in the first line of a text field?

Obviously, checking for a newline character ( \n ) works if you want to see if the cursor appears before the first line break, but testing for soft line breaks seems more complicated.

Here is a jsFiddle example to experiment with .

I don’t have a strategy yet, but I suspect that this could be due to copying the text to the cursor position in the cloned text area (or div) and creating the width as long as it should be so, don't wrap it. If the cloned area has a width less than the original width, then the cursor seems to be on the first line. There may be a simpler option, something more elegant or (best of all) an existing and well-tested solution.

Target browsers are Webkit (Chrome / Safari) and Firefox. That is, compatibility with IE is currently not a problem (if that matters).

Thank you for reading.

EDIT: Searches for the line number of the text, not the mouse cursor.

falsarella gave an excellent answer that emphasized the ambiguity of the question. What I'm looking for is that the text cursor ("carriage" may be the best word) is on the first line. I updated the question and jsFiddle to reflect.

+6
source share
2 answers

If 15 is the line height, this works (tested in firefox):

http://jsfiddle.net/h46jh/12/

 $("textarea").click(function (evt) { cursor_position = evt.pageY - $('textarea').offset().top; if (cursor_position <= 15) { alert("first line"); } else { alert("other line"); } }); 

Credits:

Find mouse position relative to element

+3
source

I know only one "working method". This method requires the use of the textarea attribute "cols". In short, set the cols to the width you need, then split the cursor position and place it to see if it is less than 1, so it = line 1!

It might be easier to explain if I just show you some sample code.

 $("textarea").live("keyup", function(e) { if ($("textarea").attr("cols")) { var cols = parseInt($("textarea").attr("cols")), curPos = $('textarea').prop("selectionStart"), result = Math.floor(curPos/cols); var msg = (result < 1) ? "Cursor is on the First line!" : "Cursor is on the line #"+(result+1); console.log($("p").text(msg).text()); }; });​ 

however, this may still require some wired math, as some col sizes can still say β€œline 2” when the cursor is just in the END of line 1 (which technically would still be correct, as any character would fall to line 2)

jsFiddle

+3
source

Source: https://habr.com/ru/post/922309/


All Articles