I am trying to build a WYSISYG editor, and I have an option to provide hyperlinking to a text selection. I have been scourging the internet but I am not able to find out why this isn't working sigh.
My understanding is, once they click on the hyperlink button, we change the background color of the selection to the selection color, then once they enter the link, we hyperlink and revert back the background color.
Here is my code for it:
const selObj = window.getSelection();
const oRange = selObj.getRangeAt(0);
rangeObjectReference.current = oRange;
if(isLinked) {
document.execCommand("unlink", false, false);
dispatch(formatBlock(blockId));
toggleLinked();
} else {
document.execCommand("backColor",true,'#ece6ff');
setBlockActive();
setLinkEnter(true);
}
Once they enter the hyperlink, I am performing this:
function appendLink() {
if(activeLink == '' && isLinked) {
document.execCommand("unlink", false, false);
dispatch(formatBlock(blockId));
toggleLinked(false);
return
} else {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(rangeObjectReference.current);
document.execCommand("backColor",false,'transparent');
document.execCommand("CreateLink", false, activeLink);
dispatch(formatBlock(blockId));
}
}
But when I change the background color of the selection, the range object is lost. and I am not able to use it to peform the hyper link. I have tried storing it and reusing the variable but it doesn't work. What is the correct method to fix this?
Thanks in advance :)
I realised that the background color gives out a span tag in your selection. All I had to do was to create a range object based on the new span text node. I tracked the text node with this function: