I know there are solutions for this problem, but I am unable to understand them or get them to work for me.
I tried copying this solution. From my understanding, const offset = sel.getRangeAt(0).startOffset
gets the cursor's position, nRange.setStart(el.childNodes[0], offset)
and nRange.collapse(true)
set nRange to start at the cursor's original position and collapse towards that point. Then sel.addRange(nRange)
is used to move the cursor to the end.
The above strategy does not seem to work for me. On the key-press, the cursor still goes to the start position of the div's text. On subsequent presses, I get the error Uncaught DOMException: Failed to execute 'setStart' on 'Range': There is no child at offset 10.
I am not entirely sure about why this error occurred, but when looking at the Watches in my debugger, I note that the offset does exceed the size of my div element's NodeList
Below is the code that gave me the above output. What changes do I have to make to stop the cursor from moving?
<html>
<body>
<div id = "thisDiv" contenteditable = "true" style="border: 5px solid black"></div>
<script>
window.onload = (event)=> {
window.addEventListener("keydown", updateText);
}
function updateText(event){
const el = document.getElementById("thisDiv");
const sel = window.getSelection();
const offset = sel.getRangeAt(0).startOffset;
if(event.keyCode == "13" || event.keyCode == "32"){
el.innerHTML += `<span>Added text </span>`;
}
const nRange = document.createRange();
nRange.setStart(el.childNodes[0], offset);
nRange.collapse(true);
sel.removeAllRanges();
sel.addRange(nRange);
}
</script>
</body>
</html>