Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 943
mpen Avatar asked Mar 01 '11 01:03

mpen


2 Answers

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.

like image 187
NakedBrunch Avatar answered Sep 25 '22 02:09

NakedBrunch


Use the following 2 functions to save and restore text selection.

function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            return sel.getRangeAt(0);
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

function restoreSelection(range) {
    if (range) {
        if (window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && range.select) {
            range.select();
        }
    }
}

Check Working example at http://jsfiddle.net/LhQda/

Type something in the TEXTAREA, then click outside the TEXTAERA to lose the selection, then click on the focus button to restore selection and focus again.

like image 21
Hussein Avatar answered Sep 25 '22 02:09

Hussein