Triggering a drop event with jQuery droppables

DA. picture DA. · Jan 22, 2014 · Viewed 8.8k times · Source

Variations of this question have been asked, but the answers are all different, somewhat dated, and aren't working for me so I'm hoping it's a matter of changed syntax rules in jQuery that I'm missing.

The scenario HTML:

<div id="theDroppable">Droppable</div>
<div id="theDraggable">Draggable</div>
<div id="theTrigger">Click to trigger a drop</div>

The jQuery:

$( "#theDroppable" )
    .droppable({
      drop: function( event, ui ) {
          alert('dropped');
      }
    });

$( "#theDraggable" ).draggable({});

$( "#theTrigger" ).click(function(){$( "#theDroppable" ).trigger('drop')});

The fiddle: http://jsfiddle.net/7Bewj/

The above creates a Droppable, a Draggable, and a div that I'd like to use to somehow trigger the function associated with the drop event on the droppable.

The draggable works fine, dragging it to the droppable and releasing triggers the alert.

The question is how can I trigger that same process without using an actual draggable...or at least without using a draggable that is dropped on top (such as by clicking the 3rd div)?

Answer

MrNobody007 picture MrNobody007 · Jan 22, 2014

As you can see from the function:

drop: function( event, ui ) {
      alert('dropped');
  }

If you define methods such as DROP during the declaration of droppable then they are called only when a DOM element(UI object) is dropped on them hence you can't trigger those function.

If you need to trigger DROP then I would suggest you to bind that event to the droppable as:

$( "#theDroppable" ).droppable({hoverClass : 'droppableStyle'});
$( "#theDroppable" ).on('drop',function(event,ui){
    alert('dropped');
});

The DROP function can now be triggered by dropping 2nd DIV or by clicking 3rd DIV as in your case. Trigger it manually using:

 $( "#theDroppable" ).trigger('drop');

NOTE: The argument 'ui' will be undefined if triggered manually, else it will contain the UI object when draggable is dropped on it.

Here is jsFiddle