Asked  7 Months ago    Answers:  5   Viewed   56 times

I'm finding tons of good, crossbrowser anwers on how to SET the cursor or caret index position in a contentEditable element, but none on how to GET or find its index...

What I want to do is know the index of the caret within this div, on keyup.

So, when the user is typing text, I can at any point know its cursor's index within the contentEditable element.

EDIT: I'm looking for the INDEX within the div contents (text), not the cursor coordinates.

<div id="contentBox" contentEditable="true"></div>

$('#contentbox').keyup(function() { 
    // ... ? 
});

 Answers

67

The following code assumes:

  • There is always a single text node within the editable <div> and no other nodes
  • The editable div does not have the CSS white-space property set to pre

If you need a more general approach that will work content with nested elements, try this answer:

https://stackoverflow.com/a/4812022/96100

Code:

function getCaretPosition(editableDiv) {
  var caretPos = 0,
    sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.rangeCount) {
      range = sel.getRangeAt(0);
      if (range.commonAncestorContainer.parentNode == editableDiv) {
        caretPos = range.endOffset;
      }
    }
  } else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    if (range.parentElement() == editableDiv) {
      var tempEl = document.createElement("span");
      editableDiv.insertBefore(tempEl, editableDiv.firstChild);
      var tempRange = range.duplicate();
      tempRange.moveToElementText(tempEl);
      tempRange.setEndPoint("EndToEnd", range);
      caretPos = tempRange.text.length;
    }
  }
  return caretPos;
}
#caretposition {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="contentbox" contenteditable="true">Click me and move cursor with keys or mouse</div>
<div id="caretposition">0</div>
<script>
  var update = function() {
    $('#caretposition').html(getCaretPosition(this));
  };
  $('#contentbox').on("mousedown mouseup keydown keyup", update);
</script>
Tuesday, June 1, 2021
 
insomiac
answered 7 Months ago
39

Here's an answer adapted from Persisting the changes of range objects after selection in HTML. Bear in mind that this is less than perfect in several ways (as is MaxArt's, which uses the same approach): firstly, only text nodes are taken into account, meaning that line breaks implied by <br> and block elements are not included in the index; secondly, all text nodes are considered, even those inside elements that are hidden by CSS or inside <script> elements; thirdly, consecutive white space characters that are collapsed on the page are all included in the index; finally, IE <= 8's rules are different again because it uses a different mechanism.

var setSelectionByCharacterOffsets = null;

if (window.getSelection && document.createRange) {
    setSelectionByCharacterOffsets = function(containerEl, start, end) {
        var charIndex = 0, range = document.createRange();
        range.setStart(containerEl, 0);
        range.collapse(true);
        var nodeStack = [containerEl], node, foundStart = false, stop = false;

        while (!stop && (node = nodeStack.pop())) {
            if (node.nodeType == 3) {
                var nextCharIndex = charIndex + node.length;
                if (!foundStart && start >= charIndex && start <= nextCharIndex) {
                    range.setStart(node, start - charIndex);
                    foundStart = true;
                }
                if (foundStart && end >= charIndex && end <= nextCharIndex) {
                    range.setEnd(node, end - charIndex);
                    stop = true;
                }
                charIndex = nextCharIndex;
            } else {
                var i = node.childNodes.length;
                while (i--) {
                    nodeStack.push(node.childNodes[i]);
                }
            }
        }

        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
} else if (document.selection) {
    setSelectionByCharacterOffsets = function(containerEl, start, end) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(containerEl);
        textRange.collapse(true);
        textRange.moveEnd("character", end);
        textRange.moveStart("character", start);
        textRange.select();
    };
}
Wednesday, June 2, 2021
 
Chvanikoff
answered 6 Months ago
35

The function you found is for finding the caret or selection in an input or textarea, not a contenteditable element. The caret/selection boundary position can be obtained in terms of a DOM node and offset within that node using the browser's Selection object to obtain a Range. I suggest reading about these objects (the links I've provided are a good starting point). In Internet Explorer, this process is completely different but you can use my Rangy library to eliminate the differences.

Friday, August 20, 2021
 
Durandal
answered 4 Months ago
26

try this

function doGetCaretPosition (oField) {

 // Initialize
 var iCaretPos = 0;

 // IE Support
 if (document.selection) { 

   // Set focus on the element
   oField.focus ();

   // To get cursor position, get empty selection range
   var oSel = document.selection.createRange ();

   // Move selection start to 0 position
   oSel.moveStart ('character', -oField.value.length);

   // The caret position is selection length
   iCaretPos = oSel.text.length;
 }

 // Firefox support
 else if (oField.selectionStart || oField.selectionStart == '0')
   iCaretPos = oField.selectionStart;

 // Return results
 return (iCaretPos);
}
Tuesday, October 5, 2021
 
Thibel
answered 2 Months ago
58

Hi i found answer for internet explorer version 8 or below

       var cursorPosition=0;    
       if (document.selection && document.selection.createRange) {
            range = document.selection.createRange();
            if (range.parentElement() == YourEditableControl) {
                var tmpEle = document.createElement("span");
                YourEditableControl.insertBefore(tmpEle, YourEditableControl.firstChild);
                var tmpRange = range.duplicate();
                tmpRange.moveToElementText(tmpEle);
                tmpRange.setEndPoint("EndToEnd", range);
                cursorPosition= tmpRange.text.length;
            }
        }

above code solve my problem to find current cursor position for IE8 or below version as window.getSelection() is undifined for IE8 or below and works fine with IE9

so one can use document.selection a selection object and range object to get current caret or cursor position form contenteditable div or other control

i hope this will help

Friday, November 12, 2021
 
fardjad
answered 3 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share