0

I see that there are a lot of answers already to achieve this using selectionStart. But unfortunately most of them are related to value of the field and not the text.

I have below code but I get Undefined

$(document).ready(function() {
  document.getElementById('span_id_1').addEventListener('keyup', e => {
    console.log('Caret at: ', e.target.selectionStart)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="span_root" type="text" id="span_id_1" contenteditable="true">Input here</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
whocaresz
  • 17
  • 4
  • Why the mix of DOM and jQuery? `$('#span_id_1').on('keyup', e => { console.log('Caret at: ', e.target.selectionStart) });` – mplungjan Apr 14 '20 at 17:33
  • Does this answer your question? [Get contentEditable caret index position](https://stackoverflow.com/questions/3972014/get-contenteditable-caret-index-position) – Triby Apr 14 '20 at 17:36
  • @mplungjan well, I don't expect that to be the problem. and I have also tried `$('#span_id_1').on('keyup', e=>{});` still failed – whocaresz Apr 14 '20 at 17:37
  • @Triby Appreciate your comment, that worked! I guess I am just bad at googling :( – whocaresz Apr 14 '20 at 17:45
  • @Triby & mplungjan, Would you know, How to force the cursor position to somewhere else? e.g if the cursor is at 8, move it to 10 automatically? – whocaresz Apr 14 '20 at 17:51

1 Answers1

0

Using this Get contentEditable caret index position

I got this

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;
}

$(function() {
  $('#span_id_1').on('mouseup',function(e) { console.log('Caret at: ', getCaretPosition(this)) })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="span_root"  id="span_id_1" contenteditable="true">Input here</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236