Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change switch position behavior

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?

like image 555
lapots Avatar asked Sep 22 '26 09:09

lapots


2 Answers

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.

like image 168
zigdawgydawg Avatar answered Sep 24 '26 23:09

zigdawgydawg


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/


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!