Ila
Ila

Reputation: 3538

Positioning of dragged, dropped & appended items using JQuery-Ui Droppable

I am using JQuery-ui draggable & droppable. I want to add dropped elements to the drop-target container, while preserving the apparent position that it had when it was dropped. Using .html() lets me preserve the position data added by the .draggable() function, but because they become children of a new element, they snap to a new position relative to that element. I experimented with helper:clone, but found that it removed all positioning information.

Here is my code, which adds dropped items to the drop target and generates a new drag item each time the previous one was dropped. It works, except that the positioning of the dropped elements is wrong- they should keep the visual position they were in when dropped.

var $foo = 1;
var bar = "drag-" + $foo;

$(".origin div").addClass(bar);

$( ".origin div" ).draggable({
  containment: ".modal"
});

$( ".droppable" ).droppable({
  accept: ".origin div",
  drop: function( event, ui ) {
    $(".droppable").append($('.origin').html());
    succeed();
  }
});


  function succeed() {
      $foo++;
      var bar = "drag-" + $foo;

      $('.origin').html("<div class='draggable'>Drag <span class='drag-num'></span></div>" );
      $(".origin div").addClass(bar);
      $( ".origin div" ).draggable({
          containment: ".modal"
      });
  }

Mark-up:

     <div class="origin">
         <div class="draggable">Drag <span class="drag-num"></span></div>
     </div>

    <div class="droppable">
       <p>accept: '#draggable'</p>
    </div>

Here it is as a JSFiddle:

http://jsfiddle.net/jrX2M/1/

Suggestions for possibilities to investigate will be highly welcome!

Upvotes: 1

Views: 2665

Answers (1)

Ila
Ila

Reputation: 3538

Solved with absolute positioning. Appending the child elements to a hidden, absolutely positioned div "accept", and manually changing child element position to "absolute":

http://jsfiddle.net/jrX2M/3/

JQuery: var $foo = 1; var bar = "drag-" + $foo;

$(".origin div").addClass(bar);

$( ".origin div" ).draggable({
  containment: ".modal"
});

$( ".droppable" ).droppable({
  accept: ".origin div",
  drop: function( event, ui ) {
    $(".accept").append($('.origin').html());
    $(".accept div").css("position", "absolute");
    succeed();
  }
});


  function succeed() {
      $foo++;
      var bar = "drag-" + $foo;

      $('.origin').html("<div class='draggable'>Drag <span class='drag-num'></span></div>" );
      $(".origin div").addClass(bar);
      $( ".origin div" ).draggable({
          containment: ".modal"
      });
  }

Mark-up:

<div class="modal">
    <div class="accept">
    </div>
    <div class="origin">
      <div class="draggable">Drag <span class="drag-num"></span></div>
    </div>

  <div class="droppable">
       <p>accept: '#draggable'</p>
   </div> <!-- end droppable -->
</div> <!-- end modal -->

Upvotes: 2

Related Questions