title: Get and set cursor position with contenteditable div
body: <p>I have a contenteditable div which I would like to be able to have users insert things such as links, images or YouTube videos. At the moment this is what I have:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function addLink() {
    var link = $('#url').val();
    $('#editor').focus();
    document.execCommand('createLink', false, link);
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;!-- Text Editor --&gt;
  &lt;div id="editor" contenteditable="true"&gt;&lt;/div&gt;
  
  &lt;!-- Add Link --&gt;
  &lt;input type="text" id="url"&gt;
  &lt;button onclick="addLink()"&gt;Submit&lt;/button&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>As you can see, the user has to type into a separate text box to enter the link address. As a result, when the link is added to the editor, it is not added to the position that the pointer/caret was on.</p>
  
  <p>My question is how I can get and set the location of the pointer/caret. I have seen other questions such as <a href="https://stackoverflow.com/questions/1181700/set-cursor-position-on-contenteditable-div">this for setting the pointer</a> however I would prefer to have a solution which is supported in all modern browsers, including Chrome, Safari, Firefox and IE9+.</p>
  
  <p>Any ideas? Thanks.</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>I found the code below which gets the position however, it only gets the position according to the line it is on. For example if I had this (where <code>|</code> is the cursor):</p>
  
  <pre><code>This is some text
  And som|e more text
  </code></pre>
  
  <p>Then I would be returned the value 7, not 24.</p>
  
  <pre><code>function getPosition() {
      if (window.getSelection) {
          sel = window.getSelection();
          if (sel.getRangeAt) {
              return sel.getRangeAt(0).startOffset;
          }
      }
      return null;
  }
  </code></pre>