How to detect the item has been dropped in the same sortable list in jQuery UI
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.
My quesiton was:
I have two connected sortable lists. My code works fine for when I drag one element from the list on the left side to the one on the right side, but can you tell me what event should I be looking for if I want to know the order of items in the left list when an item gets dragged and dropped in the same list (basically reorder the items in the same list, not dragging and dropping to the other list but to the same).
Here is the link to the code: http://jsfiddle.net/Hitman666/WEa3g/1/
So, as you will see I have an alert when items are dragged and dropped in oposite lists, but I need an event also for when the list (for example the green one) gets reordered. Then I would need to alert the order, for example: 4,3,2,1
HTML:
<ul id="sortable1" class="connectedSortable"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> <ul id="sortable2" class="connectedSortable"> <li>Item 5</li> <li>Item 6</li> <li>Item 7</li> <li>Item 8</li> </ul>
CSS:
#sortable1, #sortable2 { list-style-type: none; margin: 0; padding: 0; float: left; margin-right: 10px; }#sortable1 li, #sortable2 li { margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 120px; }#sortable1 li{background: green;}#sortable2 li{background: yellow;}
JavaScript:
$(function() { $("#sortable1, #sortable2").sortable({ connectWith: ".connectedSortable", receive: myFunc }).disableSelection(); function myFunc(event, ui) { alert(ui.item.html()); } });
The answer, by user yoelp was:
You need to use the update event. Here is my example (notice that I made 2 extra function calls to sort since you needed the evt only on the left list):
$(function(){ $( "#sortable1" ).sortable({ connectWith: ".connectedSortable", update: myFunc }).disableSelection(); $( "#sortable2" ).sortable({ connectWith: ".connectedSortable", // deactivate:myFunc }).disableSelection(); function myFunc(event, ui){ var b = $("#sortable1 li"); // array of sorted elems for (var i = 0, a = ""; i < b.length; i++) { var j=i+1; // an increasing num. a = a + j + ") " + $(b[i]).html() + '\n ' //putting together the items in order } alert(a) } });
Leave a Comment