JSFiddle - React, Tailwind, and code Playground

by jakie8

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();
    
    selection.moveStart('character', -element.value.length);
    caretPos = selection.text.length;
    
    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);
}