Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error When Destroying Draggable After Drop

I am receiving an error in jQuery UI when I attempt to destroy a draggable after dropping it. I am using jQuery 1.9.1 and jQuery UI 1.10.0.

Script

$(".drag").draggable({
    revert: "invalid",
    helper: "clone"
});

$(".drop").droppable({
    accept: ".drag",
    drop: function(event,ui){
      ui.helper.remove();
      $(this).append(ui.draggable);
      $(ui.draggable).draggable("destroy");
    }
});

HTML

<div class="drag">Draggable</div>
<div class="drop">Droppable</div>

Example: http://jsfiddle.net/feDME/

Error Received

TypeError: $(...).data(...) is undefined

I've spent the past few hours on this with no luck. I found one similar post which did not contain a resolution. Can anyone help me out here? Thanks!

like image 284
Kevin Bowersox Avatar asked Feb 18 '23 02:02

Kevin Bowersox


2 Answers

It looks like there's a race condition in the jquery-ui draggable code where it tries to set the cursor when dragging stops. The following line is failing because the "draggable" data isn't attached to the draggable div yet when stop is called.

var o = $(this).data('draggable').options;

It's a bit of a hack but this setTimeout will fix it.

$(".drop").droppable({
    accept: ".drag",
    drop: function(event,ui){
      ui.helper.remove();
      $(this).append(ui.draggable);
      setTimeout(function() {
          $(ui.draggable).draggable("destroy");      
      }, 0);      
    }
});
like image 137
clav Avatar answered Mar 06 '23 03:03

clav


I wouldn't recommend you use the setTimeout hack. The proper way to really call the destroy method on demand is to remove the special class ui-draggable-dragging before calling the destroy method. So, your code would look like this:

$(".drop").droppable({
    accept: ".drag",
    drop: function(event,ui){
      ui.helper.remove();
      $(this).append(ui.draggable);
      var dragElem = $(ui.draggable);
      // this will destroy the item
      dragElem.removeClass('ui-draggable-dragging').draggable("destroy");
    }
});

Check the draggable code, to understand what's going on and why remove this class https://github.com/jquery/jquery-ui/blob/master/ui/draggable.js#L92

like image 32
Julius Loa Avatar answered Mar 06 '23 02:03

Julius Loa