chris227
chris227

Reputation: 607

Drag and drop divs and store position

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 divs at the exact position even after refresh. My question is how can I get the position of divs 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.

Upvotes: 6

Views: 3890

Answers (1)

chris227
chris227

Reputation: 607

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

Upvotes: 2

Related Questions