Olical
Olical

Reputation: 41352

JavaScript: Stop the selection of a draggable element

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.

Upvotes: 2

Views: 1899

Answers (2)

Floyd
Floyd

Reputation: 1918

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?

Upvotes: 3

Olical
Olical

Reputation: 41352

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.

Upvotes: 1

Related Questions