user10 user10 - 6 months ago 153
HTML Question

how to swap div elements in sortable jquery?

Codepen Demo

Here i used sortable jQuery .Only Answer Block - 1,2,3,4,5 are sortable Blocks not Block 1,2,3,4,5. aboce code working only to move the elemets.

But need swap elements.

if drag 4th elements to 2nd place Result like this 1-2 4-3- -5.
the 4th place is empty.

But my expectation results like this 1-4-3-2-5

JS Code :

$(".right-block").sortable({
connectWith: '.right-block',
opacity: 0.6, cursor:"move",
cancel: ".unsortable" ,
revert:true,
items: "span",
placeholder: "highlight",
start: function (event, ui) {
ui.item.toggleClass("highlight");
ui.placeholder.height(ui.item.height());
},

stop: function (event, ui) {
ui.item.toggleClass("highlight");
}
});

T J T J
Answer

Since each item is in it's own sortable for you specific case, you can use the receive callback like:

receive: function(event, ui) {
  ui.sender.append($(this).find('span').not(ui.item));
},

Updated Pen

Judging by your use case, if you only want to swap elements I think it's better to use draggable + dropable.

Comments