4

This method...

window.getSelection().anchorNode

...tells us where the selection of text STARTS.

This method...

window.getSelection().focusNode

...tells us where the selection of text ENDS.

Since text can be selecting dragging left-to-right or right-to-left this does not INFER that the anchorNode is to the left of the focusNode.

What DOM/JavaScript method can be used to determine which referenced node is on the LEFT side of the text selection?

Clarification: this is to fix the bug for the startContainer() method (window.getSelection().getRangeAt(0).startContainer) and thus that is an invalid suggestion.

John
  • 1
  • 13
  • 98
  • 177
  • http://stackoverflow.com/questions/7486509/range-object-differences-between-webkit-and-mozilla-based-browsers – Andreas May 22 '12 at 22:04

2 Answers2

9

You would usually use Node.compareDocumentPosition() on anchorNode and focusNode, "left" is the moral equivalent of DOCUMENT_POSITION_PRECEDING (unless you have an RTL text of course). I assume that you actually want to know which comes first in the document and not the position on screen. Something like this will work:

let selection = window.getSelection();
let position = selection.anchorNode.compareDocumentPosition(selection.focusNode);
if (position & Node.DOCUMENT_POSITION_FOLLOWING)
  alert("Left-to-right selection");
else if (position & Node.DOCUMENT_POSITION_PRECEDING)
  alert("Right-to-left selection");
else
  alert("Only one node selected");
Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
  • 2
    For a full implementation you'd need to consider the case when `anchorNode` and `focusNode` are the same. For that, you need to compare `anchorOffset` and `focusOffset`. – Tim Down May 22 '12 at 23:03
  • @TimDown: Not really necessary, `compareDocumentPosition` returns 0 in this case. I've extended my example to spell out this case explicitly. – Wladimir Palant May 23 '12 at 05:23
  • 1
    Oh, I suppose you're right from the wording of the question. I assumed the OP must be wanting to find out whether the selection was backwards or not. – Tim Down May 23 '12 at 08:14
3

A method I've used for this uses the fact that setting the end of a DOM Range to be at an earlier point in the document than the start of the range will collapse the range:

function isSelectionBackwards() {
    var backwards = false;
    if (window.getSelection) {
        var sel = window.getSelection();
        if (!sel.isCollapsed) {
            var range = document.createRange();
            range.setStart(sel.anchorNode, sel.anchorOffset);
            range.setEnd(sel.focusNode, sel.focusOffset);
            backwards = range.collapsed;
            range.detach();
        }
    }
    return backwards;
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536