title: Remember cursor position after clicking away
body: <p>I have a textarea and I have some buttons that I use to add formatting to this textarea. </p>
  
  <p>The problem I'm having is that it's really bad UX because in order to add formatting you have to click a button and the textarea seems to forget the position the cursor was in. It does it fine for the click, but for the second, third etc it messes up.. I'm wondering how I can fix this. </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function formatText(type) {
      var textarea = $('#textarea');
      var cursorPos = textarea.prop('selectionStart');
      var cursorPosEnd = textarea.prop('selectionEnd');
      var v = textarea.val();
      var textBefore = v.substring(0,  cursorPos );
      var textSelected  = v.substring( cursorPos, cursorPosEnd );
      if(textSelected == "")
       textSelected = "text here"
        
      var textAfter  = v.substring( cursorPosEnd, v.length );
      textarea.val( textBefore + type + textSelected + type + textAfter );
    }</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>#textarea {
   width: 100%;
   height: 150px;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;div&gt;&lt;textarea id="textarea"&gt;
  &lt;/textarea&gt;&lt;/div&gt;
  
  &lt;button onclick="formatText('#')"&gt;Strike&lt;/button&gt; &lt;!-- For strike through --&gt;
  &lt;button onclick="formatText('_')"&gt;Italic&lt;/button&gt; &lt;!-- For italic --&gt;
  &lt;button onclick="formatText('*')"&gt;Bold&lt;/button&gt; &lt;!-- For bold --&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>So in this example, if you put your cursor in the middle of a sentence and click one of the buttons it adds the formatting where you want it. But if you click another button it doesn't add it where it should be, it adds it to the beginning. How can I fix this? Thank you.</p>