Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cursor position in a textarea (character index, not x/y coordinates)

How can I get the caret's position in a textarea using jQuery? I'm looking for the cursor's offset from the start of the text, not for the (x, y) position.

like image 234
kmunky Avatar asked Dec 11 '09 23:12

kmunky


People also ask

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 find the cursor position in text area?

If there is no selection, you can use the properties . selectionStart or . selectionEnd (with no selection they're equal). var cursorPosition = $('#myTextarea').


1 Answers

Modified BojanG's solution to work with jQuery. Tested in Chrome, FF, and IE.

(function ($, undefined) {     $.fn.getCursorPosition = function() {         var el = $(this).get(0);         var pos = 0;         if('selectionStart' in el) {             pos = el.selectionStart;         } else if('selection' in document) {             el.focus();             var Sel = document.selection.createRange();             var SelLength = document.selection.createRange().text.length;             Sel.moveStart('character', -el.value.length);             pos = Sel.text.length - SelLength;         }         return pos;     } })(jQuery); 

Basically, to use it on a text box, do the following:

$("#myTextBoxSelector").getCursorPosition(); 
like image 173
Ryan Avatar answered Sep 28 '22 01:09

Ryan