How to get selection direction in HTML?

Viewed 125

Documentation about Selection reports

A user may make a selection from left to right (in document order) or right to left (reverse of document order).

Documentation about Selection

How it is possible to distinguish the two cases, getting if the user selected starting from the begin or from the end? And if the user selected with a double click?

1 Answers

Actually, depending on direction of selection you have selection start and end in sequence or not (reverse). So creating a range with these boundaries and checking if it collapsed, gives the information needed. (Implementation in javascript)

function selectionIsBackwards(){
  var sel = window.getSelection();

  let range = document.createRange();
  range.setStart(sel.anchorNode, sel.anchorOffset);
  range.setEnd(sel.focusNode, sel.focusOffset);

  let backwards = range.collapsed;
  range.detach();
  return backwards;
}
Related