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

2
  • You should call it "cursor", "caret" usually refers to the ^ character. Commented May 22, 2015 at 9:43
  • Oh, ok my bad. I'm changing it right away ! ;) Commented May 22, 2015 at 9:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.