Created
October 29, 2012 23:21
-
-
Save ysawa/3977185 to your computer and use it in GitHub Desktop.
jQuery insertAtCaret CoffeeScript
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
jQuery.fn.extend insertAtCaret: (myValue) -> | |
@each (i) -> | |
if document.selection | |
# For browsers like Internet Explorer | |
@focus() | |
sel = document.selection.createRange() | |
sel.text = myValue | |
@focus() | |
else if @selectionStart or @selectionStart is "0" | |
# For browsers like Firefox and Webkit based | |
startPos = @selectionStart | |
endPos = @selectionEnd | |
scrollTop = @scrollTop | |
@value = @value.substring(0, startPos) + myValue + @value.substring(endPos, @value.length) | |
@focus() | |
@selectionStart = startPos + myValue.length | |
@selectionEnd = startPos + myValue.length | |
@scrollTop = scrollTop | |
else | |
@value += myValue | |
@focus() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment