JSFiddle - React, Tailwind, and code Playground
by Slava809
HTML
<div contenteditable="true" id="editable">Place the <div> </div>caret in here and press Return to move the caret 4 characters forward</div>
JavaScript
function moveCaret(win, charCount) {
var sel, range;
if (win.getSelection) {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var textNode = sel.focusNode;
var newOffset = sel.focusOffset + charCount;
sel.collapse(textNode, Math.min(textNode.length, newOffset));
}
} else if ( (sel = win.document.selection) ) {
if (sel.type != "Control") {
range = sel.createRange();
range.move("character", charCount);
range.select();
}
}
}
document.getElementById("editable").onkeypress = function(e) {
e = e || window.event;
var charCode = e.which || e.keyCode;
if (charCode == 13) {
moveCaret(window, 4);
return false;
}
};