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?

4
  • 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. Commented Jun 5, 2018 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. Commented Jun 5, 2018 at 19:53
  • 1
    Possible duplicate of disable text selection while pressing 'shift' Commented Jun 5, 2018 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 does exactly what you are asking, prevents further selection while the shift key is down. Commented Jun 5, 2018 at 20:02

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.