Search code examples
jqueryjquery-droppablejquery-draggable

Alert trigger after multiple drop events


I gotta admit, I am pretty much a noob, but I have been struggling with this one. I've got to trigger the if after both drops have happened, right now it triggers on load. What am I missing there?

$(function() {
    $( "#draggable" ).draggable({
        revert: "invalid",
        snap: "#droppable",
    });
    $( "#droppable" ).droppable({
        accept: "#draggable",
        drop: function() {
            $("#whistle").get(0).play();
            $(this).data(droppable)
        }
    });
    $( "#draggable2" ).draggable({
        revert: "invalid",
        snap: "#droppable",
    });
    $( "#droppable2" ).droppable({
        accept: "#draggable2",
        drop: function() {
            $("#whistle").get(0).play();
            $(this).data(droppable2)
        }
    });
    if ($.queue(2)) {
        $("#whistle2").get(0).play();
        alert ("done!")
    }
});

Solution

  • You could use two $.Deferreds and their promise-objects to trigger your handler:

    $(function() {
    
        var dfd1 = $.Deferred();
        var dfd2 = $.Deferred();
    
        $( "#draggable" ).draggable({
            revert: "invalid",
            snap: "#droppable",
        });
        $( "#droppable" ).droppable({
            accept: "#draggable",
            drop: function() {
                $("#whistle").get(0).play();
                $(this).data(droppable);
                dfd1.resolve();
            }
        });
        $( "#draggable2" ).draggable({
            revert: "invalid",
            snap: "#droppable",
        });
        $( "#droppable2" ).droppable({
            accept: "#draggable2",
            drop: function() {
                $("#whistle").get(0).play();
                $(this).data(droppable2);
                dfd2.resolve();
            }
        });
        //this will trigger when both dfds have been resolved
        $.when(dfd1.promise(), dfd2.promise()).then(function(){
            $("#whistle2").get(0).play();
            alert ("done!")
        });
    });
    

    See this fiddle for a demo (click both buttons and see the magic happen!) and read about $.Deferred and $.when