I had the following code:
document.getElementById("myDiv").addEventListener("keydown", function (e){
if (e.keyCode == 8) {
this.innerHTML += "⠀".repeat(4);
e.preventDefault();
}
//moves cursor
});
<div id="myDiv" contenteditable="true">Enter text.</div>
Try this.
const el = document.getElementById("myDiv");
const sel = window.getSelection();
const offset = sel.getRangeAt(0).startOffset;
el.innerHTML += 'Text needed to be added'; // perform operations here
const nRange = document.createRange();
nRange.setStart(el.childNodes[0], offset);
nRange.collapse(true);
sel.removeAllRanges();
sel.addRange(nRange);
I haven't checked in all browsers. You'll have to perform some additional steps to have browser compatibility but this is the gist of it.
Demo here: https://jsbin.com/xesitepima/edit?html,js,output
Partially taken from: https://stackoverflow.com/a/6249440/2492924