Search code examples
javascriptjqueryjquery-uijquery-ui-draggablejquery-ui-droppable

jquery draggable / droppable change snap


I am attempting to create a series of drag/droppable divs. Once div1 has been dropped, i will create a new div and have it snap at a new position. However the snap position remains the same when div1 has been dropped and div2 is being dragged: ( http://jsfiddle.net/kLpgukkj/2/ )

var trackID = "path0";
var trackType = "a";

$('.map-track-box').droppable({
    tolerance: 'touch',
    drop: function(event,ui){
        // RETURNS HOME
        $('#trackDragger').animate({ top: '30px', left: '20px' },500);
    }
});

$('#'+trackID).droppable({
    tolerance: 'touch',
    drop: function(event,ui){
        // IN POSITION
        var pos = $('#'+trackID).position();
        $('#trackDragger').animate({ top: pos.top, left: pos.left },500,function() { 
            $('#draggerBox').append("<div class='"+trackType+"' style='z-index:10;position:absolute;top:"+pos.top+"px;left:"+pos.left+"px;'></div>");
            $('#trackDragger').css({ top: '30px', left: '20px' },500);
            $('#trackDragger').attr('class', 'd');
            $('#'+trackID).removeClass('ui-droppable'); // I attempted to remove the added class, and add it to the new element, but without luck
            if(trackID=="path0") {
                trackID = "path1";
            }else if(trackID=="path1") {
                trackID = "path2";
                trackType = "d";
            }else if(trackID=="path2") {
                trackID = "path3";
                trackType = "e";
            }
            $('#'+trackID).addClass('ui-droppable');
        });
    }
});


$('#trackDragger').draggable({
    revert: 'invalid',
    start: function(event,ui) {
        $('#trackDragger').attr('class', trackType);
    },
    snap: "#"+trackID, // This keeps snapping to initial div (path0) even though trackID is being changed to path1,path2 etc
    snapMode: "inner",
    stop: function(){
        var dragPos = $('#trackDragger').position();
        if(dragPos.left < 101 && dragPos.top < 91) {
            $('#trackDragger').attr('class', 'd');
        }
        //$(this).draggable('option','revert','invalid');
    }
});

The above works well, but the dragged element keeps snapping to path0 (initial draggable div). Is there anyway to force a new snap location ?

Thank you


Solution

  • I found that adding:

    $('#trackDragger').draggable("option", "snap", "#"+trackID);
    

    will force it to snap to the new element. Furthermore using

    $('#'+trackID).droppable()...
    

    would fail, as it apparently needs to be reinitialized in order to use a different element as droppable.