Siva
Siva

Reputation: 8058

jQuery droppable - Trigger drop for given element at given position

How would you dynamically create a div and drop it in droppable div ?

This is the actual code.

   <head>
   <meta charset="utf-8">
   <title>jQuery UI Droppable - Default functionality</title>
   <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
   <script src="//code.jquery.com/jquery-1.10.2.js"></script>
   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
   <link rel="stylesheet" href="/resources/demos/style.css">
   <style>
      #draggable { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; }
      #droppable { width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px; }
   </style>
   <script>
      $(function() {
      $( "#draggable" ).draggable();
      $( "#droppable" ).droppable({
        drop: function( event, ui ) {
        $( this )
          .addClass( "ui-state-highlight" )
          .find( "p" )
          .html( "Dropped!" );
        }
      });
      });
   </script>
</head>
<body>
   <div id="draggable" class="ui-widget-content">
      <p>Drag me to my target</p>
   </div>
   <div id="droppable" class="ui-widget-header">
      <p>Drop here</p>
   </div>
</body>

Now I'm creating a new element

$("body").append("<div id='custom_1'></div>")
$("#custom_1").draggable()

How to drop #custom_1 into #droppable at a given position programmatically ?

I have tried something like this but no luck

$("#droppable").trigger('drop',$('custom_1'))

Note:

I want to trigger the event(so I can get their params event and ui) not asking this to just execute codes in drop event.

Upvotes: 2

Views: 995

Answers (1)

Irvin Dominin
Irvin Dominin

Reputation: 30993

Without rewrite the event chain you can use jQuery.simulate plugin. It is used from jQuery UI development team for jQuery UI unit testing.

Code:

$(function () {
    $("#draggable").draggable();
    $("#droppable").droppable({
        drop: function (event, ui) {
            $(this)
                .addClass("ui-state-highlight")
                .find("p")
                .html("Dropped!");
        }
    });

    $("body").append("<div id='custom_1' class='ui-widget-content'>demo</div>");
    $("#custom_1").draggable();
    var destination = $('#droppable').offset();

    $("#custom_1").simulate("drag", {
        dx: -destination.left + 50, // move to this x
        dy: -destination.top + 20, // move to this y
        speed: 5000 // set speed
    });
});

Demo: http://jsfiddle.net/IrvinDominin/ALcC4/

Upvotes: 2

Related Questions