Hi, I have worked through this section, but am interested in how to allow a user to highlight text on a page. I looked back at “Alternative Approach to find the Middle” and used
document.onmouseup = () => {
const selection = document.getSelection();
console.log(selection);
const anchorNode = selection.anchorNode;
const focusNode = selection.focusNode;
if (anchorNode != focusNode) {
// Cross-paragraph selection
return;
}
const selectedText = anchorNode.data.substring(selection.anchorOffset, selection.focusOffset);
const rangeRect = selection.getRangeAt(0).getClientRects()[0];
const dot = document.createElement("div");
dot.style.width = "5px";
dot.style.height = "5px";
dot.style.background = "red";
dot.style.position = "absolute";
// Middle
dot.style.left = `${rangeRect.x + (rangeRect.width/2)}px`;
dot.style.top = `${rangeRect.y}px`;
document.body.appendChild(dot);
}
If we use:
console.log(selectedText);
That returns the text that we select. However, if I try to do anything with this value I get errors.
selectedText.style.backgroundColor = “blue”;
does not work.
I tried
let selected = [];
selected.push(selection.data);
console.log(selected);
/* console.log(selectedText); */
let string = new String(selectedText);
selected.push(string);
But the selected array just returns undefined. I don’t understand how to extract the text value and then create a function that looks through the pages text and matches it to the selected text and then highlighting it.
Course: Intermediate JavaScript: Building Frontend Components - Learn Interactively
Lesson: Alternative Approach to find the Middle - Intermediate JavaScript: Building Frontend Components