JSFiddle - React, Tailwind, and code Playground
HTML
<p>click just right of the letter c, then just left of the letter c, note the position doesn't change</p>
<input value = "abc def"><br>
<div>caret position: <span></span></div>
JavaScript
$('input').click(function(){
$('span').text(doGetCaretPosition(this));
});
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);
}