54/121

Get the direction of the text selection

The following function returns forward if user selected text from the left to right. It returns backward in the other case.

const getDirection = function() {
    const selection = window.getSelection();
    const range = document.createRange();
    range.setStart(selection.anchorNode, selection.anchorOffset);
    range.setEnd(selection.focusNode, selection.focusOffset);

    return range.collapsed ? 'backward' : 'forward';
};

Might be useful