javascriptjqueryhtmlinputtextarea

How do you get the cursor position in a textarea?


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.

jQuery solutions preferred unless JavaScript is as simple or simpler.


Solution

  • If there is no selection, you can use the properties .selectionStart or .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.