9

How can I prevent text selection without using the traditional method e.stopPropagation (related question at bottom)?
Is there a call I can make to say "unhighlight whatever is highlighted"?

I bound mouse events on the document because there are about a hundred [more or less] elements in the page that I want to have interact with each other.

The reason I don't bind events to the elements instead is because when the mouse moves off the element, all mouse events stop triggering. I need to bind to the document to correctly watch mouse events.

The problem with using the method traditional method (link below) is that by the time the listener is triggered, the elements with text has already evaluated the mouse event.

My code works fine for Chrome. The issues below applies to Firefox.

Related Question: How can I prevent text/element selection with cursor drag
This talks about preventing bubbling to the text element with:

if(e.stopPropagation) e.stopPropagation();
if(e.preventDefault) e.preventDefault();
e.cancelBubble=true;
e.returnValue=false;
return false;
Community
  • 1
  • 1
Nyaarium
  • 1,540
  • 5
  • 18
  • 34

2 Answers2

18

Apologies for deleting my last answer but I realized it still wouldn't work in FF.

I believe that this answer, along with the CSS answer above, will produce the result you're looking for. Here is a solution that works cross-browser.

var unFocus = function () {
  if (document.selection) {
    document.selection.empty()
  } else {
    window.getSelection().removeAllRanges()
  }
} 

called onmouseup and onmousemove does the trick.

Here's the fiddle: http://jsfiddle.net/z2kpcwb6/

iamjpg
  • 7,078
  • 1
  • 16
  • 18
  • Hello! This is awesome and helps me a ton. Any idea how I can undo it once I've set it? I need to re-enable selection of text on click of a button. Thanks! – mrcoulson Dec 15 '15 at 17:49
  • The easiest way to accomplish this is by replacing the element. I forked the above fiddle and added the functionality you're talking about here: http://jsfiddle.net/iamjpg/m2xszh3m/ – iamjpg Dec 15 '15 at 18:44
  • Got it. `onmousemove = null`. – mrcoulson Dec 15 '15 at 19:38
5

you can disable selection on the element using css.

.noselect {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
spintron
  • 107
  • 10
  • ooo I forgot to mention that I have tried that already. I added that to the elements with text. Works with Chrome. Not on Firefox. It works on & off, not sure how to predict it. (in my expecience) – Nyaarium Apr 28 '15 at 00:54
  • It's a good answer tho, so i'm gonna up it. I find that the selection in Firefox is broken. Not highlighting some text, while selecting text in the middle of t he non selected. Might just be the website. – Nyaarium Apr 28 '15 at 01:25
  • Giving this one to you – Nyaarium Apr 28 '15 at 01:32