Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.getSelection(), how do you tell if the anchor node comes before the focus node?

I want to only allow selection from left to right, so the anchor node is always going to be the first node in the DOM tree (relative to the focus node).

Is there an easy way to test if the anchor node comes before the focus node?

like image 845
NullVoxPopuli Avatar asked Nov 07 '11 15:11

NullVoxPopuli


People also ask

What is anchor node in HTML?

The <a> HTML element (or anchor element), with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address.

What is selection anchor?

The anchor is where the user began the selection. This can be visualized by holding the Shift key and pressing the arrow keys on your keyboard. The selection's anchor does not move, but the selection's focus, the other end of the selection, does move.

What is getSelection in Javascript?

getSelection() The Window. getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.


1 Answers

Here's a simple way to do it that 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. I think this will break in Firefox 2, which had a bug in its handling of this, but the number of users of that browser is tiny.

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;
}
like image 150
Tim Down Avatar answered Sep 27 '22 22:09

Tim Down