Skip to content Skip to sidebar Skip to footer

How Could I Store Caret Position In An Editable Div?

I have turned a plain textarea which previously stored the users caret position and returned it when they reopened my Chrome extension. I've now changed the text area into an edita

Solution 1:

Take a look at this snippet (credit to this answer whose fiddle I have copied here):

This code listens for the mouseup and keyup events to recalculate the position of the caret. You could store it at these points.

function getCaretCharacterOffsetWithin(element) {
  var caretOffset = 0;
  var doc = element.ownerDocument || element.document;
  var win = doc.defaultView || doc.parentWindow;
  var sel;
  if (typeof win.getSelection != "undefined") {
    sel = win.getSelection();
    if (sel.rangeCount > 0) {
      var range = win.getSelection().getRangeAt(0);
      var preCaretRange = range.cloneRange();
      preCaretRange.selectNodeContents(element);
      preCaretRange.setEnd(range.endContainer, range.endOffset);
      caretOffset = preCaretRange.toString().length;
    }
  } else if ((sel = doc.selection) && sel.type != "Control") {
    var textRange = sel.createRange();
    var preCaretTextRange = doc.body.createTextRange();
    preCaretTextRange.moveToElementText(element);
    preCaretTextRange.setEndPoint("EndToEnd", textRange);
    caretOffset = preCaretTextRange.text.length;
  }
  return caretOffset;
}

var lastCaretPos = 10;

function showCaretPos() {
  /* You could store the position when you call this function */
  var el = document.getElementById("test");
  lastCaretPos = getCaretCharacterOffsetWithin(el);
  var caretPosEl = document.getElementById("caretPos");
  caretPosEl.innerHTML = "Caret position: " + lastCaretPos;
}

function restoreCaretPos() {
  var node = document.getElementById("test");
  node.focus();
  var textNode = node.firstChild;
  var range = document.createRange();
  range.setStart(textNode, lastCaretPos);
  range.setEnd(textNode, lastCaretPos);
  var sel = window.getSelection();
  sel.removeAllRanges();
  sel.addRange(range);
}

document.getElementById("test").onkeyup = showCaretPos;
document.getElementById("test").onmouseup = showCaretPos;
document.getElementById("button").onclick = restoreCaretPos;
<div id="test" contenteditable="true">This is an editable div</div>
<div id="caretPos">Caret position: 10</div>
<input type="button" id="button" value="restore caret" />

Post a Comment for "How Could I Store Caret Position In An Editable Div?"