title: how to get the correct caret position
body: <p>I'm making a contenteditable based input and I want to add emoticon support</p>
  
  <p>i have the contenteditable div, and inside is only text and IMG_TAG for emoticons. On blur, I want to save the caret position. And when I click to open the emoticon box to focus the contenteditable and set the caret where it was.  Something to simulate web.whatsapp.com behaviour</p>
  
  <p>I've found this piece of code</p>
  
  <pre><code>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 &gt; 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) &amp;&amp; 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;
  }
  </code></pre>
  
  <p>But it does not give me the correct position.</p>
  
  <p>"hello IMG_TAG john". If the cursor is just before the IMG_TAG -> the position is 6, which is correct, but if it is just after the IMG_TAG is still 6.
  Also, I didn't find a good "setCaretPosition" function to work well for me.</p>
  
  <p>I've been searching for two hours now. Anyone got a good answer ?</p>