Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering a drop event with jQuery droppables

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)?

like image 622
DA. Avatar asked Jan 22 '14 02:01

DA.


1 Answers

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

like image 76
MrNobody007 Avatar answered Oct 21 '22 10:10

MrNobody007