I am using the jQuery UI Draggable/Sortable demo (http://jqueryui.com/demos/draggable/#sortable) for the basis of my project. I need to get a reference to the <li>
that gets cloned into the sortable when the sortable receives it. I tried the sortable's receive event, but that only gives a reference to the original draggable <li>
, and not its clone.
Enable a group of DOM elements to be sortable. Click on and drag an element to a new spot within the list, and the other items will adjust to fit. By default, sortable items share draggable properties.
jQueryUI provides sortable() method to reorder elements in list or grid using the mouse. This method performs sortability action based upon an operation string passed as the first parameter.
You have one of these problems: Your jQuery or jQuery UI Javascript path files are wrong. Your jQuery UI does not include draggable. Your jQuery or jQuery UI Javascript files are corrupted.
In the demo you reference, there's actually a bug; after you drag an item down it inserts a cloned li
with an id
which is a duplicate of its brother's into the DOM, so beware (a bug was filed about this but there's no activity around it).
I did a few things to achieve this:
To get around the limitation of the demo that I described above, instead apply a class
to the draggable items that will be linked to the sortable
:
<ul>
<li class="new-item ui-state-highlight">Drag me down</li>
</ul>
Make items with that class draggable, instead of selecting an element by id
:
$(".new-item").draggable({
connectToSortable: "#sortable",
helper: "clone",
revert: "invalid"
});
Tap into the stop
event of the sortable, and perform some simple logic about the item that was dropped, leveraging the fact that an item with the class new-item
could only have been dropped (and isn't simply an existing item in the sortable):
$("#sortable").sortable({
revert: true,
stop: function(event, ui) {
if (ui.item.hasClass("new-item")) {
// This is a new item
ui.item.removeClass("new-item");
ui.item.html("<b>HI</b>");
}
}
});
Note that you could use the data-*
attribute instead of adding a helper class.
Here's a working example: http://jsfiddle.net/andrewwhitaker/twFCu/
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With