How to get selected text/caret position of an input that doesn't have focus?

mpen picture mpen · Mar 1, 2011 · Viewed 23.8k times · Source

Is it possible to (reliably) get the selected text/caret position in a input text box if that field doesn't have focus?

If not, what's the best way to get and retain this data?

Basically, when a user clicks a button I want to insert some text at the caret position. However, as soon as the user clicks that button, the field loses focus and I lose the caret position.

Answer

NakedBrunch picture NakedBrunch · Mar 1, 2011

The following script will hold the caret position and then a button click will insert text at the stored position:

Javascript:

<script type="text/javascript">
//Gets the position of the cursor
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; 
}

function InsertText() {
    var textarea = document.getElementById('txtArea');
    var currentPos = getCaret(textarea);
    var strLeft = textarea.value.substring(0,currentPos);
    var strMiddle = "-- Hello World --";
    var strRight = textarea.value.substring(currentPos,textarea.value.length);
    textarea.value = strLeft + strMiddle + strRight;
}
</script>

HTML:

<textarea id="txtArea" >Lorem ipsum dolor sit amet, consectetur adipiscing elit.</textarea>
<button onclick="InsertText();">Insert Text</button>

The script can be modified if you want to hold the caret position in a variable onblur.