How do you get the caret position in a using JavaScript?
For example: This is| a text
This should return 7>
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)]
}
Demo on JSFiddle.
See also HTMLTextAreaElement docs.