Basic jQuery plugin to allow drag and drop:
- dragging
- dropping of dragged elements
- sorting of lists and other nested html structures (
ul
,ol
,div
etc.)
- jQuery
See demo.html for a working demo.
-
Install draganddrop:
$ bower install -S gardiner/draganddrop
-
Include jQuery and draganddrop in document head:
<link href='bower_components/draganddrop/src/draganddrop.css' rel='stylesheet' type='text/css'/> <script src='bower_components/jquery/dist/jquery.min.js' type='text/javascript'></script> <script src='bower_components/draganddrop/src/draganddrop.js' type='text/javascript'></script>
-
Create html structure:
<ul id="list"> <li>Item 1</li> <li>Item 2 <ul> <li>Subitem 1</li> <li>Subitem 2 <ul> <li>Sub-Subitem 1</li> </ul> </li> </ul> </li> <li>Item 3</li> </ul> <button id="drag">Drag me</button>
-
Initialize draggable and sortable:
$('#drag').draggable(/* options/callbacks or command */); $('#list').sortable(/* options/callbacks or command */);
Options and callbacks:
handle
(string) - selector of handle element (if null the complete element will be used as handle)delegate
(string) - selector of delegate element (allows delegate-binding, delegate will be referenced as this in the event callbacks)revert
(boolean) - if true the element reverts to its origin after droppingplaceholder
(boolean) - if true a transparent clone of the element is left at the origin while draggingdroptarget
(string) - selector for valid drop targetsscroll
(boolean) - if true the scrolling parent will be automatically scrolled while draggingupdate
(function) - callback after dragging. Arguments: event, Draggable instance. This: draggable element.drop
(function) - callback after dropping on valid droptarget. Arguments: event, droptarget element. This: draggable.element
Commands:
$('#drag').draggable('destroy');
destroy
- deactivates the Draggable instance and unbinds all listeners
Limitations/Issues:
When placeholder
or revert
is set to true, click events on the draggable element would be swallowed by the generated clone. For most browsers (except Internet Explorer) this has been fixed by setting the clone to pointer-events: none;
.
Options and callbacks:
handle
(string) - selector of handle element (if null the complete element will be used as handle)container
(string) - selector for container elementsnodes
(string) - selector for node elementsautocreate
(boolean) - automatically create nested containers within nodesgroup
(boolean) - if true all elements in the jQuery object are grouped (items can dragged between them)scroll
(boolean) - if true the scrolling parent will be automatically scrolled while draggingupdate
(function) - callback after sorting. Arguments: event, Sortable instance. This: sortable element.
Commands:
$('#list').sortable('serialize');
$('#list').sortable('destroy');
serialize
- returns an object representing the structure of the nested listdestroy
- deactivates the Sortable instance and unbinds all listeners