Askerman
Askerman

Reputation: 847

Prevent text selection while dragging a mouse

I have this following JavaScript code which executes my function, when I press the left mouse and drag it across the screen:

function MyFunc(e)
{
   // I copied this part from another SO question
   e.preventDefault();
   e.stopPropagation();
   e.cancelBubble = true;
   e.returnValue = false;
   // This should cancel out all default actions, should it not?


  return false;
}

document.addEventListener('mousemove', MyFunc false);

What this is supposed to do is, that when the mouse is dragged across the screen (while the left button is pressed, then it prevents text (or any other elements) from being selected. But the reality is, that it does nothing. The function is getting executed, which I checked with console.log, but it does not prevent text selection. I can't figure out what am I doing wrong here.

What I'm using right now is this:

window.getSelection().removeAllRanges();

This works and forcefully cancels the selection, but that is pretty ugly solution and I don't understand why the code above doesn't work.

Upvotes: 2

Views: 1938

Answers (1)

Blindman67
Blindman67

Reputation: 54128

Add this to the CSS for the elements you dont want dragged.

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

Upvotes: 2

Related Questions