2

Hey there, I was just messing about in jsFiddle and attempted to make a simple drag and drop. I did not bother with getting the offset etc so as soon as you click it centers around your mouse. On mouse down I return false which I thought would stop the elements kind of 'ghost' from appearing. It did not. I focus onto the body on mouse down just in case it was that but it did not help either.

So basically my question is, how can I stop elements being selected? You can find the fiddle here: http://jsfiddle.net/Wolfy87/HY2u4/

Any help would be much appreciated. Thanks.

EDIT: I just tested it in safari and it is fine, so far it only seems to be firefox.

zero323
  • 322,348
  • 103
  • 959
  • 935
Olical
  • 39,703
  • 12
  • 54
  • 77

2 Answers2

3
jQuery.fn.extend({ 
  disableSelection : function() { 
    this.each(function() { 
      this.onselectstart = function() { return false; }; 
      this.unselectable = "on"; 
      jQuery(this).css('-moz-user-select', 'none'); 
    }); 
  } 
}); 

//How to use:
$('div.draggable').disableSelection();

Soulution without jQuery:

function disableSelection(target){ 
  if (typeof target.onselectstart!="undefined") //IE route 
    target.onselectstart=function(){return false} 
  else if (typeof target.style.MozUserSelect!="undefined") //Firefox route 
    target.style.MozUserSelect="none" 
  else //All other route (ie: Opera) 
    target.onmousedown=function(){return false} 
    target.style.cursor = "default" 
} 

found on:
Is there a way to make text unselectable on an HTML page?

Community
  • 1
  • 1
Floyd
  • 1,898
  • 12
  • 20
  • Sorry, but I am not using jQuery. It is my own library. But good concept, sticking it in a plugin. – Olical Nov 24 '10 at 14:46
  • i have post a soulution without jQuery – Floyd Nov 26 '10 at 09:11
  • Thanks for that, +1. I think I will stick with mine though because I understand it better. And it has one for IE, one for the rest. Rather than IE, Firefox and the rest. – Olical Nov 26 '10 at 10:24
  • I'd add `jQuery(this).css({ '-moz-user-select' : 'none', '-webkit-user-drag' : 'none', '-webkit-user-select' : 'none' });` to your jQuery solution for a wider browser support. – estrar Feb 20 '13 at 09:01
1

Fixed it. It turns out that I have to set the onmousedown and onselectstart functions. I assume this is the same as placing onmousedown='...' in the tag. Anyway, it is fixed now. Just go to the fiddle page.

This is basically the code that fixed it.

$('div.draggable').attribute().onselectstart = function () {
    return false;
}

$('div.draggable').attribute().onmousedown = function () {
    return false;
}

It stops the default action of selecting the element as text in Firefox and IE.

Olical
  • 39,703
  • 12
  • 54
  • 77