Given a textarea with content that flows like this
–––––––––––––––––––––––––– | This is some text, which | | wraps like this. | ––––––––
I only know of one "working method". The method requires use of textarea
's "cols" attribute. Long story short, set the cols to the width you want, then divide the cursor position and floor it to see if it is less than 1, thus it = line 1!
Might be easier to explain if I just show you a code example.
$("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 may still say "line 2" when the cursor is simply at the END of line one (which technically would still be right since any character would drop to line 2)
jsFiddle
Having that 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