Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67469

can i find caret position with respect to editable content, it gives caret postion with respect to new div when i press enter key and start writing

$
0
0

This is code for finding the caaret position:-

enter code here
getCaretPosition() {
    if (window.getSelection && window.getSelection().getRangeAt) {
      var range = window.getSelection().getRangeAt(0);
      var selectedObj = window.getSelection();
      var rangeCount = 0;
      var childNodes = selectedObj.anchorNode.parentNode.childNodes;
      for (var i = 0; i < childNodes.length; i++) {
        if (childNodes[i] == selectedObj.anchorNode) {
          break;
        }
        if (childNodes[i].outerHTML)
          rangeCount += childNodes[i].outerHTML.replace(/&nbsp;/g, "").length;
        else if (childNodes[i].nodeType == 3) {
          rangeCount += childNodes[i].textContent.replace(/&nbsp;/g, "").length;
        }
      }
      return range.startOffset + rangeCount;
    }
    return -1;
}

when 'this is the input hello caretc| is here' is my html for editable div, I expect the caret position 49 but actual caret position is 6.


Viewing all articles
Browse latest Browse all 67469

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>