javascriptselection

How to get Multi Selection direction it started from?


When developing using range in JavaScript, if you press the arrow key through keydown How to get multi-selection direction it started from? (shift + > | shift + <)

Take the string "ABC" as an example

  1. Place the cursor between A and B, Press shift + > twice -> startOffset 2, endOffset 3 -> startOffset 1, endOffset 3
  2. Place the cursor after C, Press shift + < three times And Press shift + > once -> startOffset 0 endOffset3 -> startOffset 1, endOffset 3

Both have the same offset,

  1. endOffset has been changed and 2)startOffset has been changed.

How to get multi-selection direction from arrow keydown event?

In case of multi-select, Customize the cursor when press the arrow key.

window.addEventListener("keydown", function(e) {
  let range = window.getSelection().getRangeAt(0);
  if(e.keyCode == 37) { // arrow left <
     if(~~~) {
       range.setStart(~~);
       range.setEnd(~~);
     }
  } else if(e.keyCode == 39) { // arrow right >
    if(~~~) {
       range.setStart(~~);
       range.setEnd(~~);
     }
  }
});

Solution

  • The cursor position will always be at either the start or the end of the selection - if selecting to the right (your example 1) then it's at the end / if selecting to the left (your example 2) then it's at the start.

    So you can check where the cursor is and that will give you the "direction".

    let cursorPos = window.getSelection().extentOffset;