Search code examples
javascriptjqueryjquery-uidraggabledestroy

jQuery droppable object executes destroy() but throws an error


When I run this

$('#tgsBox1').droppable({
    accept: "#tgsSquirrel",
    drop: function(e, ui) {
        ui.draggable.animate({
            left: $(this).position().left + 25,
            top: $(this).position().top + 131
        }).destroy();
    }
});

The draggable element is actually destroyed (is not draggable anymore) but it gives an error:

TypeError: ui.draggable.animate(...).destroy is not a function
ui.draggable.animate({

Looks similar to the old thread: jquery ui error for ui.draggable("destroy"), but the assumed solution (updating the jQuery-ui) doesn't sort that out.


Solution

  • The syntax for calling methods in jQuery ui dragglable widget is:

    $( ".selector" ).draggable( "method" );
    

    for destroy: $( ".selector" ).draggable( "destroy" );

    Try calling the method as follows:

    $('#tgsBox1').droppable({
      accept: "#tgsSquirrel",
      drop: function(e, ui) {
        ui.draggable.animate({
            left: $(this).position().left + 25,
            top: $(this).position().top + 131
        }).draggable("destroy");
      }
    });
    

    The reason why it isn't draggable anymore is probably because script execution stopped due to the error.

    You might want to destroy the draggable after animation is completed as well:

    $('#tgsBox1').droppable({
      accept: "#tgsSquirrel",
      drop: function(e, ui) {
        ui.draggable.animate({
            left: $(this).position().left + 25,
            top: $(this).position().top + 131
        },function(){
           ui.draggable.draggable("destroy");
        });
      }
    });