views:

37

answers:

2

Firefox has this annoying behavior that it let's the user drag and drop any image element by default. How can I cleanly disable this default behavior with jQuery?

+2  A: 

The following will do it in Firefox 3 and later:

$(document).bind("dragstart", function() {
     return false;
});

If you would prefer not to disable all drags (e.g. you may wish to still allow users to drag links to their link toolbar), you could make sure only <img> element drags are prevented:

$(document).bind("dragstart", function() {
     if (e.target.nodeName.toUpperCase() == "IMG") {
         return false;
     }
});

Bear in mind that this will allow images within links to be dragged.

Tim Down
with this solution all dragstart events will be disabled, including links (e.g. dragging your links to the URL bar)
moontear
@moontear: that's true, thanks. Edited.
Tim Down
Thank you for the updated version, it's very useful.
DjDarkman
+1  A: 

Does it need to be jQuery? You just need to define a callback function for your mousedown event on the image(s) in question with event.preventDefault().

So your image tag could look like this:

<img src="myimage.jpg" onmousedown="if (event.preventDefault) event.preventDefault()" />

The additional if is needed because otherwise IE throws an error. If you want this for all image tags you just need to iterate through the imgtags with jQuery and attach the onmousedown event handler.

There is a nice explanation (and example) on this page: "Disable image dragging in FireFox" and a not as well documented version is here using jQuery as reference: "Disable Firefox Image Drag"

moontear
If you're using an event handler attribute you can just do `onmousedown="return false;"`, which will work in all browsers.
Tim Down
I am happy with Tim Down's solution, because it is very simple, I mentioned jQuery because I thought it would be a little more complex. Thank you for your answer. Upvote.
DjDarkman