35

I have a draggable (jQuery UI) element with "canceled" text on it. Here's what I mean:

$('#main').draggable({
        cancel: '#main>* *',
        start: function(){
          // deselect text
        }
});

When I drag the element, I often select the text by accident. I want to deselect the text when the element is dragged.

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284

3 Answers3

104

To deselect everything you can use:

document.getSelection().removeAllRanges();
pimvdb
  • 151,816
  • 78
  • 307
  • 352
Eric G
  • 3,427
  • 5
  • 28
  • 52
0

jQuery UI now includes .disableSelection(), which you can use to prevent the text inside your elements from being selected. The API documentation on it isn't hugely useful, but: http://api.jqueryui.com/disableSelection/

As an aside, Eric G's answer proved supremely helpful for me when creating my own "text highlighting" tool - as Lawrence remarked, it won't throw out an error if no text has been selected.

exafred
  • 961
  • 8
  • 7
-9

Clear document selection document.selection.empty();

Something like:

 $('#main').draggable({
     cancel: '#main>* *',
     start: function(){
      // deselect text
      document.selection.empty();
     }
 });
Emmanuel N
  • 7,350
  • 2
  • 26
  • 36
  • 5
    `document.selection` is undefined in both `FF` and `Chrome`. Use `document.getSelection()` instead. – Max Jul 18 '13 at 08:44