Escher
Escher

Reputation: 5766

HTML5 draggable image "selecting" and screwing up my drag javascript in firefox

I'm trying to make an image draggable without resorting to canvas solutions (I have a lot of other DOM elements that I need for this visualisation). I have a fiddle demo here that works nicely in Chromium, but not in Firefox (I'll get around to other browsers later).

In Firefox, the image tends to get "selected" and the HTML5 draggable functionality seems to be getting invoked. This means the image tends to be getting dragged without the container div moving with it, and the image also gets selected resulting in an ugly blue overlay. I've tried to fix it with the below code, but without success (yeah, I know the z-index trick shouldn't work but I'm clutching at straws):

HTML

<div id="div1">
    <img id="pic1" draggable="false">
</div>

CSS

#div1 { z-index: 2;}
#pic1 {
    z-index: 1;
    user-drag: none; 
    -moz-user-select: none;
    -webkit-user-drag: none;
}

How to I make images play nicely while dragging in Firefox?

Upvotes: 2

Views: 1023

Answers (3)

11thdimension
11thdimension

Reputation: 10633

Use of Event.preventDefault will stop any default behavior from occurring on an event, leaving you in complete control of it.

I have placed it in every event function as below:

_on(el, 'mousedown', function (e) {
    e.preventDefault();
...

_on(document, 'mouseup', function (e) {
    e.preventDefault();
...

_on(document, 'mousemove', function (e) {
    e.preventDefault();
...

Working JS Fiddle

http://jsfiddle.net/us6t8uvd/9/

Upvotes: 1

Vale
Vale

Reputation: 2022

I remember looking around for this quite some time ago. It's actually a pretty old fix, but I've tried it on your fiddle and seems to be working.

The trick here is to add an event handler that prevents other handlers from executing when you click the mouse, like so:

onmousedown="if (event.preventDefault) event.preventDefault()"

The reason for the if is to avoid errors on older versions of IE, which won't have the function. Be aware that this can cause other events you have on mousedown to not trigger.

Finally, if you want to prevent selecting from happening, your best bet is the user-select css property.

Like the MDN page says, it's a non-standard feature, so make sure to test it, you can create a css class like so:

.noselect {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}

and use it on the items you want.

You can see both of these working in this updated fiddle: https://jsfiddle.net/us6t8uvd/10/

Upvotes: 1

Escher
Escher

Reputation: 5766

Boom! Just had an idea and tested it out. Works in FF:

#div1 {
    width: 200px;
    height: 200px;
    background-image: url('http://placehold.it/200x200?text=draggable+image');
}

Upvotes: 1

Related Questions