10

After dropping a file into a div in Firefox, the webpage will be redirected to this file. I tried to stop this propagation using jQuery's e.preventDefault() in drop handler, and failed.

See this demo, dropping a file into #test won't redirect the webpage, but dropping into #test1 will, I want to know why. Should I always bind handlers to dragenter, dragover, dragleave and drop to prevent propagation after drop?

update:

I found some tips on html5doctor:

To tell the browser we can drop in this element, all we have to do is cancel the dragover event. However, since IE behaves differently, we need to do the same thing for the dragenter event.

And Mozilla claims:

A listener for the dragenter and dragover events are used to indicate valid drop targets, that is, places where dragged items may be dropped.

But I test this demo on firefox, #test works and #test1 doesn't, seems Mozilla made a mistake, and html5doctor is right: Firefox needs dragover only to make drop work.

OpenGG
  • 4,345
  • 2
  • 24
  • 31

2 Answers2

15

The ondragover event needs to be canceled in Google Chrome and Safari to allow firing the ondrop event.

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Ahh, found one. 'A listener for the dragenter and dragover events are used to indicate valid drop targets' https://developer.mozilla.org/En/DragDrop/Drag_Operations#Specifying_Drop_Targets . But my demo works without `dragenter`: http://jsfiddle.net/mKtn2/6/ – OpenGG Jan 20 '12 at 08:47
  • 2
    Thank you! This was driving me nuts in Chrome – Matt Pileggi Jul 21 '15 at 20:40
1

I noticed that it wasn't just enough to cancel onDragOver, but I also had to cancel onDragDrop and onDragLeave. Below, I'm showing logging indicating what behavior the user is doing :

<script type="text/javascript">

    var handledragleave = function handleDragLeave(e) {
            console.log("Floating away.  Do code here when float away happens.");
            return this.cancelDefaultBehavior(e);
    }

    var handledragdrop = function handleDrop(e) {
            console.log("Dropping.  Do code here when drop happens.");
            return this.cancelDefaultBehavior(e);
    }

    var handledragover = function handleDragOver(e) {
            console.log("Floating over.  Do code here when float over happens.");
            return this.cancelDefaultBehavior(e);
    }

    cancelDefaultBehavior(e) {
            e.preventDefault();
            e.stopPropagation();
            return false;
    }

$('.your-element-being-dragged-to')
    .on('DragLeave', handledragleave)
    .on('DragDrop', handledragdrop)
    .on('DragOver', handledragover);

</script>

And then your element...

<p class="your-element-being-dragged-to">Drag something here!</p>
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133