Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent text selection on mouse drag

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;
like image 685
Nyaarium Avatar asked Apr 28 '15 00:04

Nyaarium


People also ask

How can I prevent text element selection with cursor drag?

To prevent text or element selection with cursor drag with JavaScript, we can use the window. getSelection(). removeAllRanges(); method in the selectstart event handler.


1 Answers

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/

like image 180
iamjpg Avatar answered Oct 01 '22 08:10

iamjpg