You can use one routine for both lists if you use IDs to identify each list, and classes to identify all lists that can be sorted.
In the jsFiddle demo, please note that change to your HTML.
jsFiddle Demo
Here is working code:
var lst, pre, post; //lst == name of list being sorted
$(".sortlist").sortable({
start:function(event, ui){
pre = ui.item.index();
},
stop: function(event, ui) {
lst = $(this).attr('id');
post = ui.item.index();
other = (lst == 'list1') ? 'list2' : 'list1';
//Use insertBefore if moving UP, or insertAfter if moving DOWN
if (post > pre) {
$('#'+other+ ' div:eq(' +pre+ ')').insertAfter('#'+other+ ' div:eq(' +post+ ')');
}else{
$('#'+other+ ' div:eq(' +pre+ ')').insertBefore('#'+other+ ' div:eq(' +post+ ')');
}
}
}).disableSelection();
Explanation:
When you drag an item, the first thing that happens is the start:
function. In there, we grab the current index position of the item and store it as pre
When the item is dropped, the stop:
function is executed. In here, we want to get:
a. Which list we are sorting
b. The NEW index position (so now we have the START position and the STOP positions)
c. The name of the other list
IF post
(the NEW index position) is greater than pre
(the ORIGINAL position):
a. We are moving the item DOWN, so...
b. When we programatically relocate the item in the other list we must use insertAfter
ELSE
a. We are moving the item UP in the list, so
b. We must use the insertBefore
method when moving the item in the other list.
Inside the if
statement, variable values tell jQuery which item to move and where to put it. It may help to see the code WITHOUT the variables. So, as an example, if I move the first item in List1 to the bottom of the list, here is what we want jQuery to do to the other list:
$('#list2 div:eq(0)').insertAfter('#list2 div:eq(4)');
Hope that helps.