Skip to content Skip to sidebar Skip to footer

Drag Element From Inside One Div Into Another

I want to have the capability of dragging an element from inside one div into another. jQuery UI draggable and droppable, but they seem to only manipulate the elements visually, us

Solution 1:

It is not manipulating DOM because as far as I know that's what they are designed to do.

If you want to manipulate the DOM then you can the following trick

You can use helper option, THEN when the element is dropped, read the co-ordinates and then use jQuery Clone function to clone your original div#moveMe to the drop area #secondDivAND THEN remove the original element #firstDiv > div#moveMe

Solution 2:

The functionality is fairly trivial, but may have unpredictable results. The problem is since they are, as you mentioned set with position: relative the object is going to change position from where it is dropped since it will now become relative to the new parent. To fix this you will have to recalculate the position every time you drop the object.

This can still be done fairly simply by finding the position of the past parent versus the new parent and the new offset.

This whole functionality can be accomplished like so

$(document).ready(function () {
  $( "#draggable" ).draggable();
  $( ".droppable" ).droppable({
      drop: function( event, ui ) {
        //Get the position before changing the DOMvar p1 = ui.draggable.parent().offset();
        //Move to the new parent
        $(this).append(ui.draggable);
        //Get the postion after changing the DOMvar p2 = ui.draggable.parent().offset();
        //Set the position relative to the change
        ui.draggable.css({
          top: parseInt(ui.draggable.css('top')) + (p1.top - p2.top),
          left: parseInt(ui.draggable.css('left')) + (p1.left - p2.left)
        });
      }
    });
});

Check out this CodePen for a working example: http://codepen.io/anon/pen/KfDyj/.

Post a Comment for "Drag Element From Inside One Div Into Another"