Created
March 9, 2010 11:13
-
-
Save mathiasbynens/326491 to your computer and use it in GitHub Desktop.
jQuery insertAtCaret plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I found this somewhere on the intertubes, and optimized it | |
$.fn.insertAtCaret = function(myValue) { | |
return this.each(function() { | |
var me = this; | |
if (document.selection) { // IE | |
me.focus(); | |
sel = document.selection.createRange(); | |
sel.text = myValue; | |
me.focus(); | |
} else if (me.selectionStart || me.selectionStart == '0') { // Real browsers | |
var startPos = me.selectionStart, endPos = me.selectionEnd, scrollTop = me.scrollTop; | |
me.value = me.value.substring(0, startPos) + myValue + me.value.substring(endPos, me.value.length); | |
me.focus(); | |
me.selectionStart = startPos + myValue.length; | |
me.selectionEnd = startPos + myValue.length; | |
me.scrollTop = scrollTop; | |
} else { | |
me.value += myValue; | |
me.focus(); | |
} | |
}); | |
}; |
Could you add a license and copyright?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now
sel
is added to the global scopewindow
outside of the function. Maybe addvar
in front of the declaration at line 7: