HTML5 Drag & Drop is pretty cool, it was primarily designed with the idea of dragging data in and out of the browser, but it can also be used for dragging elements inside the browser too. It doesn't support locking drags to the x or y axis, but with some smart CSS you can still provide a pretty great experience for your users.
DnD accels at moving data in and out of the browser, with the ironic exception
of IE (sadly, yes, even 11), Microsoft having designed the specification in the
first place. I don't show you how to move data in and out of the browser here,
but all of events are the same. If you are interested in that, you'll want to
look into the dataTransfer
property of the dragstart
and drop
events, it provides access to any files
and content dropped onto an element you've deemed droppable.
This example shows you how to capture the events in an Ember component, and then use them to implement swapping items through dragging.
On the homepage you'll see two buttons, Disrupt Order and Position Veritcals. If you click Disrupt Order you'll be taken to page of tiles, you can enable/disable sorting by checking the Enable Disruption check box. Drag a tile over another one to swap them. The other section Position Veritcals, was going to demonstrate inserting an item above or below an existing one in a vertical list, I ran out of time so I never finished implementing it. See "Update" below for a library that provides that functionality:
Ryan Florence is working on a series of Ember component mixins for drag and drop, so once you've poked around this project and had a laugh, I highly recommend you check it out: ic-sortable. His implementation is much more robust, has tests, and deals with inserting items not just swapping, it also adds classes to droppables so that you can show the user where the insertion will happen. He also deals with validating drops so that you can ensure your droppables only accept the correct draggables.
git clone
this repositorynpm install
bower install
ember server
- Visit the app at: http://localhost:4200
- Apple Developer - Safari Developer reference for Drag and Drop API
- Drag and Drop - MDN article on Drag and Drop
- Drag Operations - MDN article about drag operations
- MSDN - Drag and Drop in Internet Explorer
- The CSS Ninja - Blog article
- W3C HTML5 Draft - The actual working spec for HTML5 DND
- Can I Use? - Browser support