Skip to content

Instantly share code, notes, and snippets.

@reaktivo
Forked from maccman/jquery.insert.js
Created August 8, 2012 22:33
Show Gist options
  • Save reaktivo/3299449 to your computer and use it in GitHub Desktop.
Save reaktivo/3299449 to your computer and use it in GitHub Desktop.
do (jQuery) ->
$ = jQuery
insertAtCaret = (value) ->
if document.selection # IE
@focus()
sel = document.selection.createRange()
sel.text = value
@focus()
else if @selectionStart or @selectionStart is '0'
startPos = @selectionStart;
endPos = @selectionEnd;
scrollTop = @scrollTop;
@value = [
@value.substring(0, startPos),
value,
@value.substring(endPos, @value.length)
].join ''
@focus()
@selectionStart = startPos + value.length
@selectionEnd = startPos + value.length
@scrollTop = scrollTop
else
throw new Error 'insertAtCaret not supported'
$.fn.insertAtCaret = (value) ->
$(this).each -> insertAtCaret.call(this, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment