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.
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.
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();
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With