Search code examples
jqueryjquery-uidraggablepositioningdroppable

jQuery droppable absolute positioning and redraggable at the same time


I'm feeling really stupid because of this one, but I seriously can't figure it out. See I have two requirements for my Draggables, that I want to move from a scrollable side menu to another div:

  • I want them to be dropped at the position where I drop them
  • I want them to be draggable again once they are dropped

Now the stupid part is, I managed to achieve both these, but somehow can't get them to work at the same time.

When I type this the redragging works perfectly fine, but the dragged div snaps to the top left:

  jQuery('#droppable').droppable({
    accept: '.drag',
    drop: function(e, ui) {
        if (!ui.draggable.hasClass("dropped"))
            jQuery(this).append(jQuery(ui.draggable).clone().addClass("dropped").draggable());
        }
    });

But when I add code to position it, it does that fine but once it's dropped, it's dropped forever (also the original can't be dragged again)

 jQuery('#droppable').droppable({
    accept: '.drag',
    drop: function(e, ui) {
        if (!ui.draggable.hasClass("dropped"))
            var parentOffset = jQuery('#droppable').offset();
            var dropped = jQuery(ui.draggable).clone().addClass("dropped").draggable();
            dropped.css('left', (ui.position.left  - parentOffset.left) +'px');
            dropped.css('top', (ui.position.top - parentOffset.top) +'px');
       jQuery(this).append(jQuery(ui.draggable).clone().addClass("dropped").draggable());
        }
    });

I have a feeling I'm doing something very basic wrong :) Can anyone help me? Thanks in advance!


Solution

  • Okay got it. In case anyone else has this problem, this did it for me:

    jQuery('#droppable').droppable({
        accept: '.drag',
        drop: function(e, ui) {
            var parentOffset = jQuery('#droppable').offset();
            var off = $(ui.draggable).clone().offset();
    
    
            if (!ui.draggable.hasClass("dropped"))
                jQuery(this).append(jQuery(ui.draggable).clone().addClass("dropped").draggable().css({'position': 'absolute', 'left': (ui.position.left - parentOffset.left) + 'px', 'top': (ui.position.top - parentOffset.top) + 'px'}));
    
    
            }
        });