2

I'd like to get the number of characters between the start of a container and the cursor (including tags characters).

Example :

<div id="contentEditor" contenteditable="true">
    <p>This| is an<br></p><p>example.<br></p> <!-- The | represents the cursor and is not a character in the HTML -->
</div>

Here the cursor (|) should have an offset of 7, not 4.

This is because I want to add text at the cursor index. So far I'm using this answer code function called getCaretCharacterOffsetWithin. But this doesn't count tags length.

The following code should add a new paragraph at the cursor index, but I don't get the correct index:

var index = getCaretCharacterOffsetWithin(document.getElementById("contentEditor-Content"));
var content = document.getElementById("contentEditor").html();
document.getElementById("contentEditor").innerHTML = content.substring(0, index) + "<br></p><p>" + content.substring(index, content.length);

getCaretCharacterOffsetWithin code I'm using : JSFiddle

Community
  • 1
  • 1
Elfayer
  • 4,411
  • 9
  • 46
  • 76

0 Answers0