How to disable text selection with shift without disabling all text selection?

So, I know that this sounds like a duplicate, but it is not (or, if so, the accepted answer to everything I can find does not work the way I need it). The problem is this:

I write in HTML5 using jQuery, I need to make a grid that allows multi-select with control and shift. I have this logical work, but whenever you switch, it selects the text in the grid. I want to prevent this choice, but there is a critical difference between these and other issues that I found: I want the text selection to work at any other time.

Repeat: I want to disable text selection using shift WITHOUT disabling all text selection for specified elements. Does anyone know how I can do this?

- EDIT -
The following (in the constructor for the grid) solved this for me. As the interlocutor suggested, I declared a class for non-selectivity.

this.gridBody = $("#userGrid"); var handleKeydown = function(e) { e = e || window.event; var keyPressed = e.keyCode || e.which; if (keyPressed == keys.shift) { e.data.gridBody.addClass("unselectable"); } }; var handleKeyup = function(e) { e = e || window.event; var keyPressed = e.keyCode || e.which; if (keyPressed == keys.shift) { e.data.gridBody.removeClass("unselectable"); } }; $(document).on('keydown', this, handleKeydown); $(document).on('keyup', this, handleKeyup); 
+9
javascript jquery html5 css3 shift
source share
2 answers

This will bind to the document an event in which it disables text selection when pressing the DOWN shift

  document.onkeydown = function(e) { var keyPressed = e.keyCode; if (keyPressed == 16) { //thats the keycode for shift $('html').css({'-moz-user-select':'-moz-none', '-moz-user-select':'none', '-o-user-select':'none', '-khtml-user-select':'none', '-webkit-user-select':'none', '-ms-user-select':'none', 'user-select':'none' }); //or you could pass these css rules into a class and add that class to html instead document.onkeyup = function() { //here you remove css rules that disable text selection } } } 

I hope I helped you.

Based on comments

 document.onkeydown = function(e) { var keyPressed = e.keyCode; if (keyPressed == 16) { //thats the keycode for shift $('html').addClass('unselectable'); //unselectable contains aforementioned css rules document.onkeyup = function() { $('html').removeClass('unselectable'); //and simply remove unselectable class making text selection availabe } } } 
+7
source share

Another solution that you can consider: instead of preventing text from being selected, by watching the toggle keys and toggle selections, you can simply clear the text selection.

 window.getSelection().removeAllRanges(); 

I find this more convenient because it can be run in the click handler to "override" the default behavior. Appears to work in IE 9+ and other modern browsers.

+2
source share

All Articles