Skip to content

Instantly share code, notes, and snippets.

@magicmarkker
Created November 12, 2012 19:30
Show Gist options
  • Save magicmarkker/4061372 to your computer and use it in GitHub Desktop.
Save magicmarkker/4061372 to your computer and use it in GitHub Desktop.
Insert at caret
jQuery.fn.extend({
insertAtCaret: function(myValue) {
return this.each(function(i) {
var endPos, scrollTop, sel, startPos;
if (document.selection) {
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
return this.focus();
} else if (this.selectionStart || this.selectionStart === "0") {
startPos = this.selectionStart;
endPos = this.selectionEnd;
scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
return this.scrollTop = scrollTop;
} else {
this.value += myValue;
return this.focus();
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment