I am trying to insert a link into selected text, as is common with front-end editors.
I can add a link to the user's text selection like this:
var sel = window.getSelection();
var e = document.createElement("a");
e.innerHTML = sel.toString();
e.type = "link";
e.href = "www.the_link_to_open.com"
e.target = "_blank";
var range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(e)
This successfully adds an <a> tag around the selected word, with the properties needed for the added link, like this:
<a type="link" href="www.the_link_to_open.com" target="_blank">highlighted text</a>
However, the flow a user would go through in the editor is to select the word/s, then open an input where they can add the link. But, as soon as the user clicks (focuses) on the input field the window.getSelection() registers the input as the selection, which obviously makes adding the link impossible (since the selected word needs to be the selection).
I tried storing the result of window.getSelection() to use later, but this seems to dynamically change the stored value regardless. I even tried a hard(?) copy to try and store the window.getSelection() permanently using const selection = JSON.stringify(window.getSelection()) but this doesn't capture the output.
How can one keep the selection object stored when the user focuses away from the selected text?
