Skip to content

Instantly share code, notes, and snippets.

@jlstr
Created December 11, 2012 17:33
Show Gist options
  • Save jlstr/4260502 to your computer and use it in GitHub Desktop.
Save jlstr/4260502 to your computer and use it in GitHub Desktop.
Insert text at cursor position
insertAtCaret = (areaId, text) ->
txtarea = $("#t1").get(0)
scrollPos = txtarea.scrollTop
strPos = 0
br = ((if (txtarea.selectionStart or txtarea.selectionStart is "0") then "ff" else ((if document.selection then "ie" else false))))
if br is "ie"
txtarea.focus()
range = document.selection.createRange()
range.moveStart "character", -txtarea.value.length
strPos = range.text.length
else strPos = txtarea.selectionStart if br is "ff"
front = (txtarea.value).substring(0, strPos)
back = (txtarea.value).substring(strPos, txtarea.value.length)
txtarea.value = front + text + back
strPos = strPos + text.length
if br is "ie"
txtarea.focus()
range = document.selection.createRange()
range.moveStart "character", -txtarea.value.length
range.moveStart "character", strPos
range.moveEnd "character", 0
range.select()
else if br is "ff"
txtarea.selectionStart = strPos
txtarea.selectionEnd = strPos
txtarea.focus()
txtarea.scrollTop = scrollPos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment