I thought of grabbing the position of the first newline character and the last newline character and then grabbing the position of the cursor.
var firstNewline = $('#myTextarea').val().indexOf('n'); var lastNewline = $('#myTextarea').val().lastIndexOf('n'); var cursorPosition = ?????; if (cursorPosition < firstNewline) // I am on first line. else if (cursorPosition > lastNewline) // I am on last line.
- Is it possible to grab the cursor position within the textarea?
- Do you have a better suggestion for finding out if I am on the first or last line of a textarea?
If there is no selection, you can use the properties
.selectionEnd (with no selection they’re equal).
var cursorPosition = $('#myTextarea').prop("selectionStart");
Note that this is not supported in older browsers, most notably IE8-. There you’ll have to work with text ranges, but it’s a complete frustration.
I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can’t recall its name, but there seem to be dozens on articles about this subject.