Drag and drop div and save position

I'm trying to make a drag and drop script, but I'm stuck. I want to achieve: I want to drag elements on one side and put them in a div. When I move an element inside this div, my left and top positions should be calculated along the edges of the discarded div of not the whole document. so I can organize and display draggable divs in exact position even after updating. My question is how can I get the position of the divs and make an ajax call to store them in the 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

change i updated the cod, managed to get the position of the div, but it does not take it from the edge of the discarded div, it takes the position from the whole document

+5
source share
1 answer

ok I managed to get it to work as it should, here is jsfiddle and jquery, if someone needs it in the 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

+1
source

All Articles