Swapping Items in a UL

Jan 19, 2012 at 9:20 PM


Thanks alot for an amazing piece of work. This solves 90% of what I am trying to achieve.

I am implementing an iPad style application springboard. Currently with DragSort, dragging one neighbouring item ontop of another swaps them round. But when dragging non neighbouring items ontop of another, the items shuffle.

Let me try and explain.

My list order starts as....



If I drag 3 ontop of 4, they swap. So I get...


This is good.


But if I drop 1 ontop of 6 I get...


This is bad for me.


What I want to achieve by dragging 1 ontop of 6 is....



Any help would be greatly appreciated. Keep up the good work and thanks again for an excellent Codeplex project.



Feb 17, 2012 at 8:59 PM
Edited Feb 18, 2012 at 8:32 PM

Sorry for taking a while to respond.  Try making these changes to dragsort. In the dragStart function replace "list.draggedItem.attr("data-origpos", $(this).attr("data-listidx") + "-" + list.getItems().index(list.draggedItem));" with:

//store original locations of all items
$(lists).each(function(i) { this.getItems().each(function(j) { $(this).data("origpos", i + "-" + j); }); });

Next add this function:

setElmPos: function(elm, pos) {
	if (typeof pos == "undefined")
		pos = $(elm).data("origpos").split("-");
	var items = lists[pos[0]].getItems().not("[data-placeholder],[data-droptarget]"); 
	var next = items.get(pos[1]);
	if (typeof next == "undefined")
	else if (next != elm)
Then in swapItems function below "if (ei == -1 || $(nlist.pos[ei].elm).attr("data-placeholder")) return false;" add:

//restore items to their original location
$(lists).each(function(i) { this.getItems().not("[data-placeholder],[data-droptarget]").each(function(j) { if ($(this).data("origpos") != i + "-" + j) list.setElmPos(this); }); });

And further down in swapItems function below "$(nlist.pos[ei].elm).after(list.placeHolderItem);" add:

//move list item to where dragged item originally was
var pos = list.draggedItem.data("origpos").split("-");
if (!(nlist == list && ei == pos[1]) && !$(nlist.pos[ei].elm).is("[data-droptarget]")) //don't move item if dragged item was moved back to original location or if item is a droptarget
	list.setElmPos(nlist.pos[ei].elm, pos);
May 23, 2012 at 4:59 PM


I have just restarted the project I was working on with DragSort in mind and implemented the changes you suggested above and it works great. I just wanted to say a big "thank-you" and hope you will continue to maintain this excellent piece of work.