Detect selection direction in javascript

Posted on January 25, 2023

If you work with the selection in editable text elements and needs to detect the direction the user is selecting text, i.e. from right to left and vice-versa, here the snippet, found here:

var sel = getSelection(),
position = sel.anchorNode.compareDocumentPosition(sel.focusNode),
backward = false;
// position == 0 if nodes are the same
if (!position && sel.anchorOffset > sel.focusOffset || 
  position === Node.DOCUMENT_POSITION_PRECEDING)
  backward = true;