Skip to content

Instantly share code, notes, and snippets.

@dhc02
Forked from maccman/jquery.insert.js
Created March 14, 2013 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhc02/5159244 to your computer and use it in GitHub Desktop.
Save dhc02/5159244 to your computer and use it in GitHub Desktop.
(function($){
var insertAtCaret = function(value) {
if (document.selection) { // IE
this.focus();
sel = document.selection.createRange();
sel.text = value;
this.focus();
}
else if (this.selectionStart || this.selectionStart == '0') {
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = [
this.value.substring(0, startPos),
value,
this.value.substring(endPos, this.value.length)
].join('');
this.focus();
this.selectionStart = startPos + value.length;
this.selectionEnd = startPos + value.length;
this.scrollTop = scrollTop;
} else {
throw new Error('insertAtCaret not supported');
}
};
$.fn.insertAtCaret = function(value){
$(this).each(function(){
insertAtCaret.call(this, value);
})
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment