0

Please do not report this question as a duplicate. I have seen similar questions on stackoverflow, but they don't answer my specific need.

I have some text selected and highlighted on a web page and I'd like to be able to shift-click away from the selected text without extending the selection of text.

I have created a function that sets the variable shiftkey to true whenever the shift key is pressed and I have another function that gets called on a mouse click. The latter function tests if the shiftkey var is set to true to determine if I have a shift-click event. If so, I thought e.preventDefault(); would prevent extending the selected text, but it doesn't!

Using

document.getElementsByTagName("body").style.userSelect = "none";

followed by

window.getSelection().toString();

and finally

document.getElementsByTagName("body").style.userSelect = "auto";

doesn't work either!

Any ideas how this can be made to work?

Olivier
  • 607
  • 1
  • 6
  • 21
  • If you have seen similar questions here, then add links to those that are closest to your question, and explain why they don't answer your question. – t.niese Jun 05 '18 at 19:40
  • The proposed answers I have seen apply the css rule user-select: none to an element, class or id. That's not what I want to do. I'd like to still be able to get the original text selection without extending it when I shift-click away for the selection. – Olivier Jun 05 '18 at 19:53
  • 1
    Possible duplicate of [disable text selection while pressing 'shift'](https://stackoverflow.com/questions/1527751/disable-text-selection-while-pressing-shift) – t.niese Jun 05 '18 at 20:00
  • I didn't say you should tell what they did, but that you should add links to them to your question. I marked your question as a possible duplicate, because [this answer](https://stackoverflow.com/a/1529206/1960455) does exactly what you are asking, prevents further selection while the shift key is down. – t.niese Jun 05 '18 at 20:02

1 Answers1

2

I found the solution to my problem by reading this page about the selection object and this page about the range object.

I had to assign the original selection to a range and save it to a variable.

var sel = window.getSelection();
var range = sel.getRangeAt(0);

Then, after shift-clicking, the selection would get extended so I would have to empty the selection using either:

sel.empty();

or

sel.removeAllRanges();

Thereafter, I could add the original saved range to the empty selection using:

sel.addRange(range);
Olivier
  • 607
  • 1
  • 6
  • 21