I'm trying to make a drag and drop script but I'm stuck. What I want to achieve is: to drag elements from one side and put them inside a div
. When I move the element inside that div
my left and top position should be calculated from the edges of the droppable div
not the entire document. So I can arrange and display dragged div
s at the exact position even after refresh.
My question is how can I get the position of div
s and make an ajax call to store them in database. Here is my code and jsfiddle:
html
<div data-id="1" class="ui-widget-content draggable">
<p>Drag me </p>
</div>
<div data-id="2" class="ui-widget-content draggable">
<p>Drag me </p>
</div>
<div data-id="3" class="ui-widget-content draggable">
<p>Drag me </p>
</div>
<div data-id="4" class="ui-widget-content draggable">
<p>Drag me</p>
</div>
<div data-id="5" class="ui-widget-content draggable">
<p>Drag me </p>
</div>
<div id="droppable" class="ui-widget-header">
<p>Drop here</p>
</div>
<div id="pos"></div>
js
$(function() {
$( ".draggable" ).draggable
(
{
drag: function(){
var pos=$(this).attr('style');
$("#pos").html(pos);
}
});
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}
});
});
jsfiddle jsfiddle
edit
I updated the code, managed to get the position of the div
but it does not take it from the edge of the droppable div
it takes the position from the entire document.
The ondrop event attribute is used to drag an element or text and drop it into a valid droppable location or target. The drag and drop is the common feature of HTML 5. Note: By default, the images and links are draggable.
Draggable Div is a kind of element that you can drag anywhere. Here I have created a Draggable profile card.
To make an object draggable set draggable=true on that element. Just about anything can be drag-enabled: images, files, links, files, or any markup on your page. Our example creates an interface to rearrange columns that have been laid out with CSS Grid.
ok i managed to make it working as it should, here is jsfiddle and jquery if someone else need this in future. jquery
$(function() {
var pos=null;
var parent=null;
var current=null;
$( ".draggable" ).draggable
(
{
drag: function(){
pos = $(this).offset();
parent = $( "#droppable" ).offset();
current = {left: pos.left - parent.left, top: pos.top - parent.top };
$("#pos").html( current.left + ', ' + current.top );
}
});
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
$.ajax({
method: "POST",
url: "insert.php",
data: { name: current.left, location: current.top }
})
}
});
});
jsfiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With