1

with the help of some topics here I finally found a safe way to get the position of the caret / cursor in a DIV contenteditable. (Ref: Get caret position in contentEditable div )

I use the following function:

function getCaretPosition(element) {
var caretOffset = 0;
if (w3) {
    var range = window.getSelection().getRangeAt(0);
    var preCaretRange = range.cloneRange();
    preCaretRange.selectNodeContents(element);
    preCaretRange.setEnd(range.endContainer, range.endOffset);
    caretOffset = preCaretRange.toString().length;
} else if (ie) {
    var textRange = document.selection.createRange();
    var preCaretTextRange = document.body.createTextRange();
    preCaretTextRange.moveToElementText(element);
    preCaretTextRange.setEndPoint("EndToEnd", textRange);
    caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}

So thats my HTML:

<div id="result" contenteditable="true">

This is an example with <span style="color:#f00;">red</span> color<br>
This is an example with <span style="color:#f00;">red</span> color<br><br>
This is an example with <span style="color:#f00;">red</span> color

</div>

And the function always returns the correct position of the caret (like when I count it by hand ;) no matter if there are linebreaks or html elements.

In the second step I perform a server side operation with the content of my div and put the answer / "new" text back in the same div (so I replace the old content with the new content, but there are no character operations, just insertion of html tags to mark several words for example, positions of letters doesnt change).

After using for example $("#result").html(modifiedtext); the caret will be placed at the beginning of the div. Here is the problem: I want the caret to be set at the same position as before performing the text-replacement operation.

All of the examples and functions I found dont work with multiline contenteditable divs.

I would really appreciate it if someone could show me or explain how I achieve this functionality. Pure js or jquery is fine.

  • Does [this thread](https://stackoverflow.com/questions/6249095/how-to-set-caretcursor-position-in-contenteditable-element-div) help? – Michael Hurley Sep 18 '18 at 15:28
  • 1
    I tried this a f** hundred times but it never correctly. Now I gave it a completely new try and the Answer from Liam works, I have to add an offset of 6 to "my" position of the cursor but at least it works. Thanks for bringing this to my attention! – Simon Aschemeier Sep 18 '18 at 15:39

0 Answers0