Write the paragraph, select with the mouse or the node map; see anchor and focus, direction, per-node offsets, and the Range that is always in order. An…
Text editors, a "quote" button, comment highlights, translate-on-select: they all read the Selection. The bugs are classic: a reversed direction, an offset taken for a position in the paragraph, or a selection that turns out to be outside your element.
A selection is two points (node + offset), and its direction follows how you highlighted
focusOffset is always bigger than anchorOffset Highlighted right to left, the focus comes before the anchor. Use sel.getRangeAt(0) (start always before end) or sel.toString(); sel.direction exists in newer browsers too.sel.anchorOffset without checking its node That offset is a position inside anchorNode, not in your paragraph, and the selection may well be in another element. Check p.contains(sel.anchorNode) first; for the position in the paragraph, measure a Range from p’s start to the anchor, then toString().length.setInterval Listen for selectionchange on document: it fires for the mouse, the keyboard and changes made in code. A 100 ms poll asks 10 times a second even when nothing changed.<b>Rara</b> anchorNode and focusNode become two different text nodes, each with its own offset.isCollapsed is true and type is Caret: an empty selection is still a selection, with anchor = focus.modify('extend', 'forward', 'word') a few times The focus jumps a word at a time, the anchor stays put. All through the API, and selectionchange still fires.