...

/

Alternative Approach to find the Middle

Alternative Approach to find the Middle

The previous approach didn't work, so we'll try to use a different approach to find the middle of the cursor.

We'll cover the following...

The range property

Our previous attempt of wrapping the text we want in a span and getting the position of the span didn’t work. Time to Google for another lead. Searching for “get position of text”, I find a range property which I saw in the getSelection API but hadn’t paid attention to.

Press + to interact
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);
console.log(selection.getRangeAt(0).getClientRects());
}
widget

Ah, this is exactly what we need! Sometimes we do extra work trying to use the tools we’re familiar with. Part of being an experienced frontend engineer is just knowing what exists. As you progress, you gain valuable intuition about what’s possible and what’s impossible, what tasks are straightforward, and which are minefields (ahem- CSS animations), which solutions degrade the user experience and which solutions are cheap on CPU, and then some. This ...