How do I disable the text selection on the right-click?

3

I do not want to disable text selection, nor do I want to disable the right click. I want to ONLY disable text selection with the right-click (but the menu should still appear when right clicking and select text by double-clicking or clicking + drag should also continue to work)

    
asked by anonymous 06.04.2015 / 20:36

2 answers

3

There are two ways using CSS (as far as I know):

  • pointer-events: none : Makes the mouse pointer interaction with the element being passed to the back element. This makes it impossible to click on the element itself, and in the case of a button ... will render it useless. Also, if you start the selection from the previous element, then it will be possible to select the text.

    To work, you could make the element that contains text have pointer-events: none , the element underneath it is that it actually opens the menu.

  • user-select: none : Prevents element text from being selected. Each browser handles this in a different way because it is not standardized by W3C. So it is necessary to use manufacturer prefixes: -moz , -webkit and -ms . Already tried to standardize this , but is no longer part of CSS3 .

    Note from MDN:

      

    Note: user-select is currently part of any W3C CSS specification.   As such, there are minor differences between the browser   implementations. Be sure to test your application across browsers.

06.04.2015 / 21:44
2

You can take advantage of the event that opens the context menu, and clear any selection from there:

document.addEventListener('contextmenu', function(e) {
    window.getSelection().removeAllRanges();
});

I recommend testing this across multiple browsers because the selections API is not yet stable. See also % method documentation , as well as the material available for removeAllRanges and Selection , available from the method link.

    
06.04.2015 / 21:36