JSFiddle - React, Tailwind, and code Playground

by Christian Gambardella

HTML

<div contenteditable="true" class="textfield">&nbsp;</div>

CSS

.textfield {
    width:200px;
    height: 100px;
    border: 1px solid grey;
    padding: 5px;
}

JavaScript

function doGetCaretPosition (ctrl) {
    var CaretPos = 0;
    // IE Support
    if (document.selection) {
        ctrl.focus ();
        var Sel = document.selection.createRange ();
        Sel.moveStart ('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
        CaretPos = ctrl.selectionStart;
    return (CaretPos);
}
 
function setCaretPosition(ctrl, pos)
{
    if(ctrl.setSelectionRange)
    {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

$(".textfield").focus(function() {
    setCaretPosition($(this).get(0), 0);
    return false;
});