What I am trying to achieve:
I have a contenteditable div (notably neither a textarea nor an input). As a user edits the content of that div, they may leave the div and click a button elsewhere on the page to insert a span (which contains predefined chinese characters) into the div. I need that span to go into the div at the point of selection. For now I am assuming that the selection will simply by the last caret position.
What I have managed so far:
I got the character offset of the caret and stored it elsewhere on the page. I then grabbed the offset and attempted to insert at it using range.insertNode
. However, I noted that the offset I was grabbing was the number of characters so I was getting an error saying that there was no node at my offset.
I then read this: https://javascript.info/selection-range <-- This made me realise that groups of characters were being treated as "nodes". So, having just realised that my offset should be a node value, this is where I'm at for apply the span in the right place (I think it'll work):
function insertAtOffset(parent, child, offset = 0){
range = document.createRange();
range.selectNode(parent);
range.setStartBefore(parent.childNodes[offset]);
range.insertNode(child);
}
However, I'm back to square one in terms of getting the node offset at which to insert.
I think the solution may be related to:
var node = document.getSelection().anchorNode;
which i've taken from: Get element node at caret position (in contentEditable) but I'm unsure how to get the node offset in a way that would help with my span input function.
Specific question:
How can I get the node offset at the current caret position?
I will use several events to store this location and then insert at it when the user clicks the button for the Chinese character.
Note: I feel a little deeper in the Front End than I am comfortable with. Therefore, I will upvote any answers that provide additional context or information that promotes my understanding of the problem and/or the solution.