1

Within a Contenteditable I try to change something during runtime. To replace the text with an element, so to speak. Whenever I replace the text, the caret-position resets to 0, my p-tag consists of many other elements like b, i, span and sometimes there is also a . If I replace the with a , the caret position is reset to the beginning. I simply lack a logical approach how to get for example the new caret position behind the new element. I think I already have most of the topics through here on this topic. Therefore I will now ask my first question here.

JSFidle: https://jsfiddle.net/eLv6p9kj/3/

Code JS:

function clickFunctionMouse(){
     let text = $("#pelement").html();
      //Replace the text with a image. 
     text = text.replace('<span>Text <b>sample</b><span>', '<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png">')
     //Setting new HTML to Element. But how to get Caret-Position of the new Element?
     $("#pelement").html(text);
}
$('#pelement').on("input", clickFunctionMouse);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
To show my problem, dont edit the text inside the span element..

<p contenteditable="true" id="pelement"><b>Hello</b> How are <i>you</i> <span>Text <b>sample</b><span> I dont know what else I could write <b>here!</b></p>

Many thanks in advance for the help from rainy Germany and good night.

Harrikan
  • 11
  • 1
  • 2
  • It works well and the problem is not clarified. Show, please, desired result/output. – Aksen P Jan 18 '20 at 00:39
  • @Aksen P: I have changed the example so that the problem can be seen better – Harrikan Jan 18 '20 at 08:58
  • Still not clear what you're trying to achieve. Are trying to get the caret to appear at the beginning of the element that is added to the editable p on input? Perhaps a combination of the following might help: 1. Get element offset relative to parent - https://stackoverflow.com/questions/11634770/get-position-offset-of-element-relative-to-a-parent-container 2. Set caret position - https://demo.vishalon.net/getset.htm – Nivi M Jan 18 '20 at 11:07
  • I would like to achieve that when the HTML is replaced, the cursor is no longer placed at the start, but is saved and placed again at the position after insertion. Alternatively, it is enough for me to get the position of the cursor behind the inserted element. – Harrikan Jan 18 '20 at 11:12

0 Answers0