Skip to content Skip to sidebar Skip to footer

How To Place The Caret Where It Previously Was After Replacing The Html Of A Contenteditable Div?

I have a contenteditable div where I replace hashtags with clickable links when the user clicks on space or on enter. The user writes down: I love but there is no fish at home| H

Solution 1:

rangy.js has a text range module that lets you save selection as indices of the characters that are selected, and then restore it. Since your modifications do not alter innerText, this looks like a perfect fit:

var sel = rangy.getSelection();
      var savedSel = sel.saveCharacterRanges(this);
      $(this).html(html);
      sel.restoreCharacterRanges(this, savedSel);

Implementing this manually requires careful traversal of the DOM inside contenteditable and careful arithmetics with the indices; this can't be done with a few lines of code.

Your placeCaretAtEnd can't possibly place the caret after the link you've inserted, since it doesn't "know" which (of the possibly multiple) link it is. You have to save this information beforehand.

/**
* Trigger when someone releases a key on the field where you can post remarks, posts or reactions
*/
$(document).on("keyup", ".post-input-field", function (event) {

       // if the user has pressed the spacebar (32) or the enter key (13)if (event.keyCode === 32 || event.keyCode === 13) {
          let html = $(this).html();
          html = html.replace(/(^|\s)(#\w+)/g, " <a href=#>$2</a>").replace("<br>", ""); 
          var sel = rangy.getSelection();
          var savedSel = sel.saveCharacterRanges(this);
          $(this).html(html);
          sel.restoreCharacterRanges(this, savedSel);
       }
  });
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><scripttype="text/javascript"src="https://cdnjs.cloudflare.com/ajax/libs/rangy/1.3.0/rangy-core.js"></script><scripttype="text/javascript"src="https://cdnjs.cloudflare.com/ajax/libs/rangy/1.3.0/rangy-textrange.js"></script><divcontenteditable="true"class="post-input-field">
I love (replace this with #sushi and type space) but there is no fish at home
</div>

Post a Comment for "How To Place The Caret Where It Previously Was After Replacing The Html Of A Contenteditable Div?"