5

Playing with drag and drop and while I can seem to drag fine, I can't seem to drop.

Here's my playground: http://jsfiddle.net/KZ8RD/1/

Basically, the dragstart and dragend events on the draggable node seem to fire fine. But I have yet to trigger any event on that target nodes.

# Source handlers
$('#source')
  .on('dragstart', (e) -> log '#source dragstart', this, e)
  .on('dragend',   (e) -> log '#source dragend',   this, e)

# Target Handlers
$('#cells td')
  .on('dragenter', (e) -> log 'target dragenter',  this, e)
  .on('dragleave', (e) -> log 'target dragleave',  this, e)
  .on('dragover',  (e) -> log 'target dragover',   this, e)
  .on('drop',      (e) -> log 'target drop',       this, e)​​​

So what conditions need to exist for the target's dragenter and drop events to fire? I'm clearly missing some of them.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337

1 Answers1

6

You've been bitten by one of the many quirks of the HTML5 draggable API: You need to attach some data to the drag event, or else it will be ignored by potential drop targets. The fix is to add the line

e.originalEvent.dataTransfer.setData 'text/html', 'foo'

to the dragstart event. (Note that e.dataTransfer won't work because the dataTransfer property isn't copied onto e by jQuery, at least as of 1.7.) Working fork of your playground: http://jsfiddle.net/AK2zJ/

Note that this will give you dragenter and dragover, but not drop... as the aforementioned article points out:

For the drop event to fire at all, you have to cancel the defaults of both the dragover and the dragenter event.

You can do this in jQuery by returning false from each of those events. Here's an example with that modification as well, allowing the drop event to occur: http://jsfiddle.net/YaEBj/

In addition to this kludginess, it's worth mentioning that there are serious flaws in the HTML5 draggable API. Really, the only good reason to use it (instead of something like jQuery UI) is if you want to enable drag-and-drop operations across multiple browser windows.

Community
  • 1
  • 1
Trevor Burnham
  • 76,828
  • 33
  • 160
  • 196
  • Interesting... That sort of data wouldn't always be required to do what you want, so it seems odd to require it. Also, now `drop` wont fire (an in fact fires `dragleave` (wtf)) but that is probably another question entirely. – Alex Wayne Jul 19 '12 at 22:45