4

I am experiencing an issue with the jQuery-UI draggable and droppable. The issue that I'm facing is the fact that:

When I move an element from one div to another (during dragging using .append() ) it shifts the element away from the mouse cursor jarringly.

I know what causes it the left / top css positions are no longer correct since I'm moving from one relative div to another. But a fix for it I can't find.

I have tried quite a few "solutions" :

  • Changing the cursorAt position http://api.jqueryui.com/draggable/#option-cursorAt while dragging but this only goes in affect after mouseup and on the next mousedown.
  • Changing the css during dragging: http://api.jqueryui.com/draggable/#event-drag which while it works is not ideal since it has hiccups that make it flicker and move in random directions which is highly annoying.
  • Making the draggable div absolute instead of relative (Which locally in my backbone application so far has the 'best' results but is still far from desirable since i require the elements in the sidebar to be relative so they append nicely one below the other )

Here is my JSBin example of my issue.

JavaScript

var positionStack = [];
var fieldview = $('#field');
var sidebarView = $('#sidebar');

$('.draggable').draggable({
  containment: ".container",
  zIndex: 100,
  cursorAt: {
    top: 20,
    left: 25
  },
  snap: '.sidebar',
  snapMode: 'inner'
});

$('#field').droppable({
  over: function(event, ui) {
    dragOverElement({event: event, ui:ui});
  }
});

 $('#sidebar').droppable({
   over: function(event, ui) {
     dragOverElement({event: event, ui:ui});
   }
 });

function dragOverElement(data){
  var me = this;
  var lastItem = positionStack[positionStack -1];
  if(lastItem !== data.event.target.id)
  {
    positionStack.push(data.event.target.id);
    var player = $(data.ui.draggable);
    var target = data.event.target.id;
    switch(target)
    {
      case ('field'):
        fieldview.append(player);
        player.css('position', 'absolute');
        break;
      case ('sidebar'):
        sidebarview.append(player);
        player.css('position', 'absolute');
        break;
    }
  }
}
Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
N.Schipper
  • 1,668
  • 3
  • 18
  • 25
  • I know this is a very old question, but just wanted add my 2 cents. I faced this exact issue. But I was able to solve it using "cursorAt". I see that you already have it in place. Just wanted to suggest anyone looking at this now or even you - just play with the values of cursorAt and see if you could achieve the desired result. – Souvik Ghosh Sep 21 '16 at 08:08
  • Logic issue here: `positionStack[positionStack -1]`. Think this should be `positionStack[positionStack.length -1]`. This seems like a problem for the first pass. – Twisty Dec 19 '17 at 23:18
  • Testing here: https://jsfiddle.net/Twisty/61yo6jmy/ – Twisty Dec 19 '17 at 23:38

0 Answers0