Search code examples
javascriptjquery-uidrag-and-dropdroppable

jQuery UI Drag and Drop: Target picks up incorrect droppable area


I've been tearing my hair out over this strange behaviour despite lots of Googling!

I have created a draggable div element, and a series of droppable divs which should highlight when hovered over. When I click and drag, my helper behaves as expected, but my droppable divs don't... the droppable element half a screen to the right of the mouse is the one that gets highlighted, which seems especially strange as the y-axis seems to work properly. Here's a simplified and anonymised fiddle of what I'm trying to do that shows the behaviour: Fiddle

I believe it might have something to do with me using appendTo in the draggable function, which I want to keep to move my item across divs. Is this where I'm going wrong?

A lot of my Googling finds people struggling with scrolls on a page, but I don't have any x-axis scrolling at all here.

Here's the code that's also in the fiddle:

var bucket_string = "#Bucket1";
var div_defect = document.createElement("div");
div_defect.className = "item";
div_defect.innerHTML = "Item 1";
$(bucket_string).append(div_defect);

$('.item').draggable({
    appendTo: '#workspace',
    helper: 'clone',
    cursor: 'move',
    revert: true,
});


  $('.item').bind("drag", function (event, ui) {
      var width = $('.item').width();
      ui.helper.css("width", width);
      ui.helper.css("font-size", "x-small");
  });

  $('.Bucket').droppable({
      accept: '.item',
      hoverClass: 'hovered',
  })


Solution

  • Finally worked it out!

    This was happening because (as per the fiddle posted) my CSS was setting the width of my draggable items to 100% of their parents. When I used appendTo: '#workspace' on the clone they inherited the width of the entire workspace momentarily throwing their position out by half a screen.

    Not sure if this was my incompetence or a specially crafted 'feature' but setting the width of the items to an absolute number of pixels sorted me out.