1

I wanted to get current cursor position in a textbox using JQuery. Cursor position may change using keyboard arrow keys, while typing or mouse press. Is there a way to get this done.

var currentCursorPosition = $("#textbox").currentCursorPosition();
Nishantha
  • 6,065
  • 6
  • 33
  • 51
  • 3
    This question has been already answered Check this http://stackoverflow.com/questions/1891444/cursor-position-in-a-textarea-character-index-not-x-y-coordinates – Sachin Nov 12 '15 at 06:41

2 Answers2

2

With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:

function getCaret(el) {
  if (el.selectionStart) {
    return el.selectionStart;
  } else if (document.selection) {
    el.focus();

    var r = document.selection.createRange();
    if (r == null) {
    return 0;
    }

    var re = el.createTextRange(),
    rc = re.duplicate();
    re.moveToBookmark(r.getBookmark());
    rc.setEndPoint('EndToStart', re); 

    return rc.text.length;
  }
  return 0;
}

source: Caret position in textarea, in characters from the start

Community
  • 1
  • 1
0

Fiddle: This solves my problem.

<textarea id="textarea" style="width:80%;height:100px;"></textarea><br/>
<input type="text" id="indicator" style="width:30px;">

JavaScript:

var indicator   = document.getElementById("indicator");
var textarea    = document.getElementById("textarea");
setInterval(function() { indicator.value = caret(textarea);}, 100);

function caret(node) {
     if(node.selectionStart) return node.selectionStart;
     else if(!document.selection) return 0;
     //node.focus();
     var c= "\001";
     var sel= document.selection.createRange();
     var txt= sel.text;
     var dul= sel.duplicate();
     var len= 0;
     try{
          dul.moveToElementText(node);
     }
     catch(e){
            return 0;
     }
     sel.text= txt + c;
     len= (dul.text.indexOf(c));
     sel.moveStart('character',-1);
     sel.text= "";
     return len;
}

Source: Source page

Nishantha
  • 6,065
  • 6
  • 33
  • 51