Skip to content

Instantly share code, notes, and snippets.

@sfengyuan
Created December 19, 2017 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfengyuan/8291cac7cc358ebe269c25d07bec4bcc to your computer and use it in GitHub Desktop.
Save sfengyuan/8291cac7cc358ebe269c25d07bec4bcc to your computer and use it in GitHub Desktop.
Insert text to textarea
/**
* Insert <text> to <areaId>, then [selectedText] will be selected.
*
* @export module.insertAtCaret
* @param {string} areaId - ID of textarea
* @param {string} text - text to be inserted
* @param {string} [selectedText=undefined] - a sub string of param <text>,
* will be selected after insertion, and also be replaced by the current selected text in textarea
*/
export function insertAtCaret (areaId, text, selectedText = undefined) {
const txtarea = document.getElementById(areaId)
if (!txtarea) {
console.log('Error: insertAtCaret, element not found. id:', areaId)
return
}
const scrollPos = txtarea.scrollTop
let caretPos = txtarea.selectionStart
const front = (txtarea.value).substring(0, caretPos)
const back = (txtarea.value).substring(txtarea.selectionEnd)
let userSelected
if ((txtarea.selectionEnd - caretPos) > 0 && selectedText) {
userSelected = txtarea.value.substring(caretPos, txtarea.selectionEnd)
text = text.replace(selectedText, userSelected)
}
txtarea.value = front + text + back
if (selectedText === undefined) {
caretPos = caretPos + text.length
txtarea.selectionStart = caretPos
txtarea.selectionEnd = caretPos
} else if (userSelected) {
const offset = text.indexOf(userSelected)
txtarea.selectionStart = caretPos + offset
txtarea.selectionEnd = caretPos + offset + userSelected.length
} else {
const offset = text.indexOf(selectedText)
txtarea.selectionStart = caretPos + offset
txtarea.selectionEnd = caretPos + offset + selectedText.length
}
txtarea.focus()
txtarea.scrollTop = scrollPos
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment