7

I am wondering how those drag and drop widgets cancel text selection in the dragging element and other elements in the page. I tried the following code which works in IE8 (cannot select text) but does not work (can still select text) in Firefox.

<!DOCTYPE html>
<html>
<body>
  <p>Hello World</p>
  <script type="text/javascript">
    document.onmousemove = function() {
      return false;
  }
  </script>
</body>
</html>
powerboy
  • 10,523
  • 20
  • 63
  • 93

2 Answers2

8

Or, analagous to your IE8 solution for Moz:

document.body.style.MozUserSelect="none"
Matthew Smith
  • 1,287
  • 1
  • 9
  • 19
5

There was a case where I had a horizontal scrollbar and text on the page was being selected while dragging the scroll bar. I used jQuery to add an "unselectable" class to the body when my scrolling start function fired off, and removed the class when my scrolling stop function executed. Like so:

function startDrag(event){
    $('body').addClass('unselectable');

    // start drag code
}

function stopDrag(event){
    $('body').removeClass('unselectable');

    // stop drag code
}

And this is what the unselectable class looked like in my CSS doc.

.unselectable {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
Smooth Customer
  • 113
  • 2
  • 6
  • To make this even more efficient (and only barely longer), we can use document.body.classList.add('unselectable'); and document.body.classList.remove('unselectable'); to eliminate the need to (re)select the body tag from the DOM for each instance of these events, which I feel should be as responsive as possible for the user. Though, I'm just now seeing this issue in Chrome, today, for the vertical scrollbar, and have to wonder why it's happening at all?! – Troy Niemeier Dec 29 '22 at 19:45