Working Solution
tl;dr: Refer to this Fiddle for a working answer.
I looked everywhere for a solution to the issue of dragging multiple selected items from a sortable into a connected sortable, and these answers were the best I could find.
However...
The accepted answer is buggy, and @Shanimal's answer is close, but not quite complete. I took @Shanimal's code and built on it.
I fixed:
I added:
- Proper Ctrl + click (or Cmd + click if on a mac) support for selecting multiple items. Clicking without the Ctrl key held down will cause that item selected, and other items in the same list to be deselected. This is the same click behavior as the jQuery UI
Selectable()
widget, the difference being that Selectable()
has a marquee on mousedrag.
Fiddle
HTML:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<ul>
<li>Four</li>
<li>Five</li>
<li>Six</li>
</ul>
JavaScript (with jQuery and jQuery UI):
$("ul").on('click', 'li', function (e) {
if (e.ctrlKey || e.metaKey) {
$(this).toggleClass("selected");
} else {
$(this).addClass("selected").siblings().removeClass('selected');
}
}).sortable({
connectWith: "ul",
delay: 150, //Needed to prevent accidental drag when trying to select
revert: 0,
helper: function (e, item) {
var helper = $('<li/>');
if (!item.hasClass('selected')) {
item.addClass('selected').siblings().removeClass('selected');
}
var elements = item.parent().children('.selected').clone();
item.data('multidrag', elements).siblings('.selected').remove();
return helper.append(elements);
},
stop: function (e, info) {
info.item.after(info.item.data('multidrag')).remove();
}
});
NOTE:
Since I posted this, I implemented something simmilar - connecting draggable list items to a sortable, with multi-select capability. It is set up almost exactly the same, since jQuery UI widgets are so similar. One UI tip is to make sure you have the delay
parameter set for the draggables or selectables, so you can click to select multiple items without initiating a drag. Then you construct a helper that looks like all the selected elements put together (make a new element, clone the selected items, and append them), but make sure to leave the original item intact (otherwise it screws up the functionality - I cannot say exactly why, but it involves a lot of frustrating DOM Exceptions).
I also added Shift + Click functionality, so that it functions more like native desktop applications. I might have to start a blog so I can expound on this in greater detail :-)