With jQuery UI, is it possible to execute a drag & drop operation using javascript?
Example. When the link is clicked, drag the #pony
and drop it into the #box
. I've tried triggering the drag event but that doesn't seem work :)
$('#pony').trigger('drag', [$('#box')]);
This is how the jQuery UI team programmatically trigger drop
event.
draggable = $( "#draggable1" ).draggable(),
droppable1 = $( "#droppable1" ).droppable( config ),
droppable2 = $( "#droppable2" ).droppable( config ),
droppableOffset = droppable1.offset(),
draggableOffset = draggable.offset(),
dx = droppableOffset.left - draggableOffset.left,
dy = droppableOffset.top - draggableOffset.top;
draggable.simulate( "drag", {
dx: dx,
dy: dy
});
The simulate
function is defined in jquery.simulate.js. In simple words, it moves the draggable onto the droppable to trigger the drop
event.
Putting this altogether, we have the following snippet. Cheers.
$(function() {
$("#draggable").draggable();
$("#droppable").droppable({
drop: function(event, ui) {
console.log(event, ui);
alert('dropped!');
}
});
});
function trigger_drop() {
var draggable = $("#draggable").draggable(),
droppable = $("#droppable").droppable(),
droppableOffset = droppable.offset(),
draggableOffset = draggable.offset(),
dx = droppableOffset.left - draggableOffset.left,
dy = droppableOffset.top - draggableOffset.top;
draggable.simulate("drag", {
dx: dx,
dy: dy
});
}
#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;
}
br {
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
<script src="https://rawgit.com/jquery/jquery-ui/1-11-stable/external/jquery-simulate/jquery.simulate.js"></script>
<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>
<br>
<button onclick="trigger_drop()">trigger drop event</button>