Skip to content

Instantly share code, notes, and snippets.

@jawdatls
Created May 11, 2015 08:34
Show Gist options
  • Save jawdatls/467482225eae03ec3aec to your computer and use it in GitHub Desktop.
Save jawdatls/467482225eae03ec3aec to your computer and use it in GitHub Desktop.
jQuery insert text at caret
$.fn.extend({
insertAtCaret: function(myValue) {
var obj;
if( typeof this[0].name !='undefined' ) obj = this[0];
else obj = this;
if ($.browser.msie) {
obj.focus();
sel = document.selection.createRange();
sel.text = myValue;
obj.focus();
}else
if($.browser.mozilla || $.browser.webkit) {
var startPos = obj.selectionStart;
var endPos = obj.selectionEnd;
var scrollTop = obj.scrollTop;
obj.value = obj.value.substring(0, startPos)+myValue+obj.value.substring(endPos,obj.value.length);
obj.focus();
obj.selectionStart = startPos + myValue.length;
obj.selectionEnd = startPos + myValue.length;
obj.scrollTop = scrollTop;
}else{
obj.value += myValue;
obj.focus();
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment