Dart: Getting elements to accept drops using HTML5 DnD

Using HTML5 Drag-n-Drop could be little bit tricky, because it doesn’t work out of the box. If you want to listen to on-mouse-down or on-key-down events on an element, you would do it like this:

HtmlElement element = queryselector("#my-element");
element.onMouseDown.listen((MouseEvent e) {
  print("Please don't click me hard next time! Thanks for understanding :)");
});

So, it should be that simple to get on-drop event to work right? No!
If you try this code, you will be disappointed to find out that, it doesn’t work at all.

HtmlElement element = queryselector("#my-element");
element.onMouseDown.listen((MouseEvent e) {
  print("Drop 'em on me!");
});

So why?
From the beginning of HTML, when you drop something into a web page, it is thought to be a link and the browser tries to navigate there.

So? So, you have to disable this default behavior. This is how you do it:

HtmlElement element = queryselector("#my-element");
element.onDrop.listen((MouseEvent e) {
  print("Don't drop 'em too fast, you could break them.");
});

element.onDragOver.listen((event) {
  event.preventDefault();
});

Can you notice how we prevent default behavior in onDragOver event by calling preventDefault on the event? That does the trick!

Happy Darting!!!!