I need a script to place the caret of a contenteditable div
right after the last character typed.
Simply typing a character doesn't work, since I have other scripts dealing with CJK character convertion, changing the div's innerHTML
at each onInput
event (and thus, resetting the caret position every time).
I am using the code in this SO answer to get the current position of the caret, inside the contenteditable div
.
I am storing the caret position generated from the code above in the browser's localStorage
.
Whenever I need to set the caret position at the desired place, I call the following function , where pos
is the value stored + 1:
function setCursor(pos) {
var tag = document.getElementById("editableDiv");
var setpos = document.createRange();
var set = window.getSelection();
setpos.setStart(tag.childNodes[0], pos);
setpos.collapse(true);
set.removeAllRanges();
set.addRange(setpos);
tag.focus();
}
Everything works fine for all the text inside the div up until its first child. From there onwards, it no longer works, and I get the following error in the console:
Uncaught DOMException: Index or size is negative or greater than the allowed amount
I also tried changing my function showCaretPos()
for the function SetCaretPosition(el, pos)
in this other similar SO post. But, again, it stops working from the first child onwards, this time, with the error InternalError: too much recursion
.
How can I fix this, having it work regardless of the existance of children elements?