0

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?

Here is my code.

MikeMichaels
  • 454
  • 1
  • 6
  • 25
  • Does this answer your question? [Set Caret Position in 'contenteditable' div that has children](https://stackoverflow.com/questions/36869503/set-caret-position-in-contenteditable-div-that-has-children) – Recep Karadas Oct 12 '20 at 13:29
  • Not really. I tried replacing my `setCursor(pos)` function for the `SetCaretPosition(el, pos)` in the answer you mentioned. I get the error `InternalError: too much recursion`. – MikeMichaels Oct 12 '20 at 14:37
  • @Recap Karadas It works as fine as the code I currently have. Which means it breaks at the first child, working fine until there. – MikeMichaels Oct 12 '20 at 15:09
  • 1
    Actually I didn't add an answer, because I tested my mentioned answer before I flagged your question as duplicate. Here is the fiddle that works perfectly imho [http://jsfiddle.net/4j5y6p0g/](http://jsfiddle.net/4j5y6p0g/) (Comments begin with "RK:"). – Recep Karadas Oct 12 '20 at 17:16

0 Answers0