I'm making a simple web-app for fun that lets users select text and highlight it in yellow (or whatever color, doesn't matter). Here is what I have so far:
function replaceSelectedText() {
var sel, range;
var replacementText, spanTag;
if (window.getSelection) {
replacementText = window.getSelection().toString();
spanTag = document.createElement("span");
spanTag.className = "highlighted";
spanTag.appendChild(replacementText);
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
//range.insertNode(document.createTextNode(replacementText));
range.insertNode(spanTag);
}
} else if (document.selection && document.selection.createRange) {
replacementText = '<span class="highlighted">' + document.selection.createRange().text + '</span>';
range = document.selection.createRange();
range.text = replacementText;
}
}
document.onmouseup = replaceSelectedText;
document.onkeyup = replaceSelectedText;
I had it working where it would highlight the selected phrase, but I was just using a replace() call on the body's HTML so if the user selected a common word like "a", the first occurrence of "a" would be highlighted rather than the one they clicked.
Am I on the right track with the code I have so far, or should I still use the replace() call? Replace seems like it would work, but I can't seem to get the array index of where the selected word occurs, and the range doesn't seem to return a very useful value.
Thanks in advance.