How do I disable selecting text at the right click?

Asked

Viewed 394 times

3

I don’t want to disable text selection, nor do I want to disable right-click. I JUST want to disable the selection of text With the right mouse click (but the menu should still appear when right click and, select text via double click or click + drag should also continue working)

  • I don’t know how it works in Windows, but on Mac, if you click with the right mouse button on any word (even if it is inside another element, like a button), besides Open menu, the word is selected.

  • @user23536 understood, unfortunately I do not have a MAC to test the situation, but maybe I post an example, the situation is only on the same Mac?

  • @Guilhermenascimento I did a Google search and it seems to me that it is only on the same MAC.

  • I believe that mouse events are compatible and we can block by the event itself contextmenu, using textrange or something like that, the night I try to add an answer.

  • @Guilhermenascimento ok, thank you for your attention. :)

  • 1

    Take a look at this answer: http://stackoverflow.com/questions/2326004/prevent-selection-in-html

Show 1 more comment

2 answers

3

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

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

    To work, you could make the element containing text have pointer-events: none, the element below it actually opens the menu.

  • user-select: none: prevents the element text from being selected. Each browser treats this differently as it is not standardized by W3C. Therefore it is necessary to use manufacturer prefixes: -moz, -webkit and -ms. We have tried to standardize this, but is no longer part of CSS3.

    Note from the MDN:

    Note: user-select is not 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.

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 on multiple browsers as the selections API is not yet stable. See also documentation of the method removeAllRanges, as well as the material available for Selection and Range, available from the method link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.