I have a textarea and I would like to know if I am on the last line in the textarea or the first line in the textarea with my cursor with JavaScript.
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?
jQuery solutions preferred unless JavaScript is as simple or simpler.
Here's a cross browser function I have in my standard library:
Use it in your code like this:
Here's its complementary function:
http://jsfiddle.net/gilly3/6SUN8/
If there is no selection, you can use the properties
.selectionStart
or.selectionEnd
(with no selection they're equal).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.
Here is code to get line number and column position
tArea is the text area DOM element
I've done a fair amount of work on this and posted a function for getting caret/selection position in textareas on Stack Overflow several times. Unlike pretty much every other code to do this out there, it works properly with line breaks in IE < 9.
Here's an example question with some background:
Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?
And here's a link to a jQuery plug-in I've written that includes this function and other selection-related textarea functions:
https://github.com/timdown/rangyinputs
getCursorPos() function will return the cursor position in GWT