I am trying to create a div where, when the user right clicks on a word, it becomes red. This div is editable, so the user can change the text in it.
<div contenteditable="true" id="test"><span class="word">text</span></div>
So far, what I have done is, every time the event listener "input" is called, I loop through all the spans in the div and use regular expressions on their content to match them with (spaces)(words) or (words)(spaces). Then, i add a new span after the current one that contains the second matched part, and replace the content of the current span by the first matched part. I also add the class word to the span that contains the words, depending on the expression that was matched.
So Far this approach words, and I am able to right click on individual words to either put them in red or not.
My problem however is that when I insert and remove spans inside my contenteditable div, the location of the caret changes. The reason for this is probably because the length of the html inside the div changes more than the length of the text.
How could I make it so that after I type, paste or remove some text in the div, and that after my function separates the spaces from the characters in different spans, the caret remains exactly where it was.
In other terms, I would like to store the current caret position, modify the html(not the text) of my div, and then restore the previous caret position.
Does anyone have an idea regarding how I could proceed? Thanks for the help!