JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id="textarea" autocomplete="off">
Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text
</textarea>
CSS
#textarea {
width: 450px;
height: 500px;
}
JavaScript
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0') {
iCaretPos = oField.selectionStart;
}
// Return results
return (iCaretPos);
}
(function ($) {
$(document).ready(function () {
var $textarea = $('#textarea');
$textarea.bind('keypress', function (e) {
var caret_start = doGetCaretPosition($textarea[0]);
alert(caret_start);
});
});
})(jQuery);