'Disable selection of current word when right-clicking on an element

I've enabled right-click on an element, like so:

<div class=my-content (contextmenu)="openContextMenu($event)">

In my handler, I've added the necessary commands to tell it not to open the browser's context menu:

openContextMenu( $event ) {
  // do my thing, and then:

  $event.preventDefault();
  $event.stopPropagation();
  return false;
}

Unfortunately, the browser is selecting the word that I clicked on, which junks up the user experience. This is happening on both Safari and Chrome.

How do I tell the browser NOT to highlight the word I clicked on?



Solution 1:[1]

You may just use the ::selection css pseudo-element

::-moz-selection {
    color: black; /* your text colour */
    background: transparent;
}

::selection {
    color: black;
    background: transparent;
}

Before the ::selection you can specify the css selector like so:

p::selection {}

Solution 2:[2]

One way is to disable the selection of text on a specific element or class. to do so you can use plain simple css. May Be This Can Help You

Solution 3:[3]

On Mac Safari, if there is no selected text (i.e. window.getSelection().type !== "Range"), right clicking selects the word that was clicked on.

Others have provided solutions to make the entire element non-selectable, or to make the selection transparent. However, that doesn't work when you want to let users select normally (via left click drag), but just want to disable word selection with right click.

You can get around this by getting selection state using mousedown event. It works because mousedown event fires before the word gets selected. (Timing: mousedown -> word selection -> contextmenu)

selectionType = window.getSelection().type

document.addEventListener("mousedown", (ev) => {
  if (ev.button === 2) { // right click
    selectionType = window.getSelection().type
  }
})

document.addEventListener("contextmenu", (ev) => {
  if (selectionType !== "Range") {
    window.getSelection().removeAllRanges() // don't select text
  }
  event.preventDefault()
  event.stopPropagation()

  // do whatever
})

Note: Adding ev.preventDefault() inside mousedown event handler does not work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 loveJS
Solution 2
Solution 3 BlueGreenMagick