JSFiddle - React, Tailwind, and code Playground
HTML
Type in some text in the textarea below, including newlines. Then try to set the caret, and if you try to set it past a newline, the results are skewed. IE7/8<br /><br />Caret Pos: <input type="text" id="toSet"> <input type="button" onclick="setCaret()" value="Set then Get Pos"><br />
<textarea id="textarea"></textarea>
<pre id="log"></pre>
CSS
body{
padding:10px;
}
textarea{
margin:20px;
min-height:80px;
width:380px;
height:202px;
font-size:13px;
font-family:monospace;
}
JavaScript
function getCaret(){
var element = document.getElementById('textarea');
element.focus();
var selection = document.selection.createRange();
if(selection === null) return 0;
var re = element.createTextRange(),
selection_copy = re.duplicate();
re.moveToBookmark(selection.getBookmark());
selection_copy.setEndPoint('EndToStart', re);
caretPos = selection_copy.text.length;
text = selection_copy.text;
if(text.indexOf("\r\n")) {
caretPos -= (text.split("\r\n").length - 1);
}
document.getElementById('log').innerHTML += ', Retrieved as Pos: '+caretPos;
}
function setCaret(){
var pos = document.getElementById('toSet').value,
range = document.getElementById('textarea').createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
document.getElementById('log').innerHTML = 'Set Caret to: '+pos;
setTimeout(getCaret, 1000);
}