If you don't have to support IE, you can use selectionStart
and selectionEnd
attributes of textarea
.
To get caret position just use selectionStart
:
function getCaretPosition(textarea) {
return textarea.selectionStart
}
To get the strings surrounding the selection, use following code:
function getSurroundingSelection(textarea) {
return [textarea.value.substring(0, textarea.selectionStart)
,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]
}
See also HTMLTextAreaElement docs.