Kevin Bowersox Kevin Bowersox - 5 months ago 32
Javascript Question

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!

Answer

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);      
    }
});