public
Last active

  • Download Gist
jquery.insert.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
(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);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.