jQuery Draggables and Droppables Positioning
Asked Answered
E

1

5

I'm using jquery UI and jQuery draggable, all my draggables use jquery clone helper and appends the draggable to droppable.

Here is my code

 $('#squeezePage #droppable').droppable({
  tolerance: 'fit',
  accept: '#squeezeWidgets .squeezeWidget',
  drop: function(event, ui) {
   var dropElem = ui.draggable.html();

   var clone = $(dropElem).clone();

   clone.css('position', 'absolute');
   clone.css('top', ui.absolutePosition.top);
   clone.css('left', ui.absolutePosition.left);

   $(this).append(clone);

   $(this).find('.top').remove();
   $(this).find('.widgetContent').slideDown('fast');

   $(this).find('.widgetContent').draggable({
    containment: '#squeezePage #droppable',
    cursor: 'crosshair',
    grid: [20, 20],
    scroll: true,
    snap: true,
    snapMode: 'outer',
    refreshPositions: true
   });

   $(this).find('.widgetContent').resizable({
    maxWidth: 560,
    minHeight: 60,
    minWidth: 180,
    grid: 20,
   });
  }
 });

I'm setting the position of the clone with .css('top', ui.absolutePosition.top); and css('left', ui.absolutePosition.left); but the position is relative to the BODY.

The position is not relative to the droppable which makes the draggable drop to random places. Overall, the droppable and draggable integration is not tight. I want to make it smoother.

Extended answered 12/4, 2010 at 22:23 Comment(0)
E
10

I'm getting the offset of body and subtracting it from the offset of the widget clone.

clone.css('top', ui.position.top - droppableOffset.top);
clone.css('left', ui.position.left - droppableOffset.left);

It works!

Extended answered 13/4, 2010 at 11:45 Comment(2)
where droppableOffset variable is jQuery('#squeezePage #droppable').offset();Extended
I spent so many hours looking for a similar solution.. thank you so much.Danica

© 2022 - 2024 — McMap. All rights reserved.