Sunday, November 22, 2015

jQuery UI Drag & Drop with "Clone"

The problem I was trying to solve is how to drag an element, make a clone on drop, then make the dropped element draggable with different parameters. Seemed like a simple task, given the basics that are built into jQuery UI. It turns out that there a lot of posts out there that give part of the answer, but I have not found one that gives a complete example. Marcos Placona came close with his example, but it seemed overly complex and it also had an interesting bug:
  1. Drag one of the widgets on the left and drop in the grid (fine).
  2. Drag the widget you just dropped (fine).
  3. Now, drag any widget on the left to an invalid place, so as to force an animation back, and see what happens!
There seems to be some phantom association between the previously dropped element and the draggable element used by jQuery UI, either through direct reference or an ID.

I was about to adopt his code, but having found this bug I thought I should try on my own, given all the examples I have seen. I ended up building a much simpler working example with half the code.

A few notes on the code:
  1. The condition in the beginning of the drop() function filters out the case where you drag a widget that has already been dropped in the drop area.
  2. I set the position of the dropped element to "absolute" so that it can float inside the drop area.
  3. To calculate the drop position within the drop area, you need to calculate the offset of the dropped element from its parent, rather than from the page origin (which are the coordinates you get in the event).
  4. Note that you have to call css() on element before you append it or else the position may not take effect!
  5. Finally, for the code nazis out there, I deal with the repetition in the CSS via SASS when I develop locally! 

No comments:

Post a Comment