It's important for me to know the difference between clicking before one letter versus after the previous, even though both cases might look the same on screen. This is because the meaning can be carried through the number of spans that are nested. An example:
<span id="x-container"><span id="x">x</span></span><span id="y">y</span>
<script>
document.addEventListener('selectionchange', e => {
var selection = window.getSelection();
if (selection.type =='Caret')
console.log(selection.anchorNode.textContent,selection.anchorOffset)
})
</script>
The console.log()s look as follows:
clicking on the x slightly left-of-center, we get x 0 (correct)
clicking on the x slightly right-of-center, we get x 1 (correct)
clicking on the y slightly left-of-center, we get x 1 again: WRONG!!!!
clicking on the y slightly right-of-center, we get y 1 (correct)
How can I fix this third case so I can tell whether we clicked before y versus after x? I tried adding a dummy span between the two but it didn't work.
Note that the x and y look a little close to each other here. In the actual thing I'm doing, I'm adding padding so it doesn't look as strange and is easier to click before y vs after x. Just take my word for it that adding padding/margin doesn't change the problem...
Since you are only interested in the selectionchange events that were triggered by a mouse event, you can check which element received the mousedown event that did trigger this selectionchange event.
You just have to store it in a variable accessible to your selectionchange handler, then if it's not the Selection's anchorNode, or doesn't contain it, you know that the browser messed up.
You then have to check if the actual target was before or after to correctly find the new anchorOffset:
let activeElem = null;
document.addEventListener('selectionchange', e => {
const selection = window.getSelection();
let { anchorNode, anchorOffset } = selection;
if (anchorNode === selection.focusNode) {
if (activeElem && (!activeElem.contains(anchorNode))) {
const isBefore = activeElem.nextElementSibling.contains(anchorNode);
anchorOffset = isBefore ? activeElem.textContent.length : 0;
anchorNode = activeElem;
}
console.log(anchorNode.textContent, anchorOffset);
}
})
document.addEventListener("mousedown", e =>
// here you can change the selector from "span" to anything more restrictive
// as long as it matches your "targetted" elements
activeElem = e.target.matches("span") ? e.target : null
);
document.addEventListener("mouseup", e => activeElem = null);
<span id="x">x</span><span id="b">b</span>