How to get the caret column (not pixels) position in a textarea, in characters, from the start?

Restless Wanderer picture Restless Wanderer · Nov 4, 2008 · Viewed 163k times · Source

How do you get the caret position in a <textarea> using JavaScript?

For example: This is| a text

This should return 7.

How would you get it to return the strings surrounding the cursor / selection?

E.g.: 'This is', '', ' a text'.

If the word “is” is highlighted, then it would return 'This ', 'is', ' a text'.

Answer

Christian C. Salvad&#243; picture Christian C. Salvadó · Nov 4, 2008

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(node) {
  if (node.selectionStart) {
    return node.selectionStart;
  } else if (!document.selection) {
    return 0;
  }

  var c = "\001",
      sel = document.selection.createRange(),
      dul = sel.duplicate(),
      len = 0;

  dul.moveToElementText(node);
  sel.text = c;
  len = dul.text.indexOf(c);
  sel.moveStart('character',-1);
  sel.text = "";
  return len;
}

(complete code here)

I also recommend you to check the jQuery FieldSelection Plugin, it allows you to do that and much more...

Edit: I actually re-implemented the above code:

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; 
}

Check an example here.