How to set the reverse selection?

I am working on a custom textarea based token field. The idea is to have a text box with div elements located above so that they look like text.

It has been a pain so far, but I managed to do almost everything except one.

Is it even possible to set the reverse selection in javascript? When you place the cursor somewhere in the middle of the text field, hold down the key and press the left arrow several times, you will get a choice. The difficult part is that it is not ordinary - it is the opposite (it starts from the very end, and not as usual). There are placeholders in my text box over which I show my divs (tokens). When you go to one of them, the cursor jumps to the opposite edge of the placeholder, so it feels natural. When you hold the shift and reach the placeholder, it moves to the right and it sets a new choice, so it looks like you have selected the token (you can click "Delete" and delete the selected range using the token itself, which is very cool), BUT it will not work if you move from right to left,because setting a new highlight will make it uncured:

Selection from left to right:

abcde[start]efg[end](token)
[shift]+[right]
abcde[start]efg(token)[end]
[del]
abcde

Right to left selection

(token)[end]efg[start]abcde
[shift]+[left]
[start](token)abcdeefg[end] //see? it back to normal
[shift]+[left]
[start](token)abcdeef[end]g //huh?! shift-right moves end point (unexpected)
abcde

So here is the question: can I set the selection in textarea where the starting point would be larger than the ending point? Just element.setSelectionRange(right, left)doesn't work in firefox, any other ideas?

+5
source share
1 answer

After several experiments in the Firebug console, I think this is not trivial. However, you can catch the keypress event:

If the user presses the left arrow, you need to continue the selection on the left and return false. Then, by default, the browser is not called, but the user still has a feeling of choice on the left.

textarea.onkeypress = function (event) {
  if (!event){event = window.event; /* %#$! IE */ }
  if (event.shiftKey && event.keyCode == 37 /* left */) {
    event.target.selectionStart = currentSelectionStart - 1;
  }
  return false;
};

37 - left arrow, 38 - up, 39 - right, and 40 - down.

+1
source

All Articles