2

How to change switch behavior in sortable? I mean by default there 1 - 2 - 3 - 4 http://jsfiddle.net/keGuN/ when I switch positions of 4 and 1 - they transform into 4 - 1 - 2 - 3. I want only switch positions of 4 and 1(4 - 2 - 3 - 1). How to do it?

lapots
  • 12,553
  • 32
  • 121
  • 242
  • When I want to switch positions of two elements - other elements change their positions too. `1 2 3 4` -> want to switch `4`&`1` -> but new order is `4 1 2 3`. I want only change positions of `4` and `1` so the result should be - `4 2 3 1` – lapots Sep 11 '13 at 17:46

2 Answers2

5

I think I understand what you are trying to do. jQuery's Sortable isn't really designed to do what you are asking. However, playing with the events that Sortable exposes, you can swap positions of the dragged item (A) with the item that was previously in the spot (B) where A was dropped. I think this achieves the effect you want:

jsFiddle demo

jQuery:

$(function() {
    var oldIndex;

    $("#sortable").sortable({
        start: function(event, ui) {
            oldIndex = ui.item.index();
        },
        stop: function(event, ui) {
            var newIndex = ui.item.index();
            var movingForward = newIndex > oldIndex;            
            var nextIndex = newIndex + (movingForward ? -1 : 1);

            var items = $('#sortable > div');

            // Find the element to move
            var itemToMove = items.get(nextIndex);
            if (itemToMove) {

                // Find the element at the index where we want to move the itemToMove
                var newLocation = $(items.get(oldIndex));

                // Decide if it goes before or after
                if (movingForward) {
                    $(itemToMove).insertBefore(newLocation);
                } else {
                    $(itemToMove).insertAfter(newLocation);
                }
            }
        }
    });

    $("#sortable").disableSelection();
});

The only noticeable issue is that the positions are not update on drag, but only after the item is dropped in its new location.

zigdawgydawg
  • 2,046
  • 13
  • 10
5

You can achieve swapping with draggable/droppable

$(function() {
$(".swapable").
draggable({ revert: true }).
droppable({
    drop:function(event,ui){
        swapNodes($(this).get(0),$(ui.draggable).get(0));
    }});
});

https://stackoverflow.com/a/698440/2033671

function swapNodes(a, b) {
    var aparent= a.parentNode;
    var asibling= a.nextSibling===b? a : a.nextSibling;
    b.parentNode.insertBefore(a, b);
    aparent.insertBefore(b, asibling);
}

http://jsfiddle.net/keGuN/1/

Community
  • 1
  • 1