Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 
  • 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.

like image 602
Chev Avatar asked Oct 12 '11 20:10

Chev


People also ask

How do I find the cursor position in text area?

First, get the current position of cursor with the help of property named as selectionStart on textarea/inputbox. To insert the text at the given position we will use slice function to break the string into two parts and then we will append both parts to the text(text_to_insert) in front and end of the text.

How do I change the cursor position in textarea?

To set the cursor at the end of a textarea: Use the setSelectionRange() method to set the current text selection position to the end of the textarea. Call the focus() method on the textarea element. The focus method will move the cursor to the end of the element's value.

How do I get the cursor position in HTML?

If you ever had a specific case where you had to retrieve the position of a caret (your cursor's position) inside an HTML input field, you can do so using the selectionStart property of an input's value. Keep in mind that selectionStart can only be retrieved from the following list of input types: text. password.


1 Answers

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.

like image 138
pimvdb Avatar answered Sep 21 '22 09:09

pimvdb