1

I've seen lots of question about caret position. Most of them are very old.

I have a div with children that has content editable set to true.

  <div tabindex="-1" id="id0"  contenteditable="true" >
    <p class="circle"></p>
    <p class="corner"></p>
    text here
  </div>

  function getCaretPosition(element) {
    let element2 = $(element).get(0);
    let caretOffset = 0;

        let range = window.getSelection().getRangeAt(0);
        let preCaretRange = range.cloneRange();
        preCaretRange.selectNodeContents(element2);
        preCaretRange.setEnd(range.endContainer, range.endOffset);
        caretOffset = preCaretRange.toString().length;

    return caretOffset;
}

setInterval(function(){
console.log(getCaretPosition(document.getElementById("id0")));
},1000);

When I get the caret, it appears to be offset, depending on child elements of the div. How can this be fixed? I don't want to hard code the offset.

https://jsfiddle.net/nm9zjLma/2/

sanjihan
  • 5,592
  • 11
  • 54
  • 119
  • try https://stackoverflow.com/questions/4767848/get-caret-cursor-position-in-contenteditable-area-containing-html-content – davidchoo12 Oct 14 '17 at 08:53

0 Answers0