0
votes

I have 6 options to drag and drop in 6 droppable area. The droppable area should not have more one dragged element. If a droppable area has already an element and dropped another one it should just shift existed element to next sibling element.

I want exactly like jquery sortable but this should work like this after dragging and dropping.

Find fiddle demo here.

$(".qselected").sortable();
$(".qselected").disableSelection();

$(".qitem").draggable({
    containment : "#container",
    helper : 'clone',
    revert : 'invalid'
});

$(".qselected, #qlist").droppable({
    hoverClass : 'ui-state-highlight',
    drop : function(ev, ui) {

    if($('.qselected div').length){
        //$('.qselected div').eq(0).remove().appendTo();
    } 
    $(ui.draggable).clone().appendTo(this);
    $(ui.draggable).remove();

        $(".qitem").draggable({
            containment : "#container",
            helper : 'clone',
            revert : 'invalid'
        });
    }
});
1
I think what you want is to drag into the sortable. In draggable, make use of connectToSortable option. - Twisty

1 Answers

1
votes

Not sure about the sortable portion based on your description, but here is one way to handle the droppable:

Example: http://jsfiddle.net/Twisty/s08pf0g9/

JavaScript

$(document).ready(function() {
  $(".qselected").sortable();
  $(".qselected").disableSelection();

  $(".qitem").draggable({
    containment: "#container",
    revert: 'invalid'
  });

  $(".qselected, #qlist").droppable({
    hoverClass: 'ui-state-highlight',
    drop: function(ev, ui) {
      var $item = ui.draggable.detach();
      var $target = $(ev.target);

      if ($target.find(".qitem").length === 0) {
        console.log("Target is empty, dropping here.");
        $item.attr("style", "");
        $item.appendTo($target);
      } else {
        console.log("Target is full.");
        $(".qselected").each(function(i, el) {
          if ($(el).find(".qitem").length === 0) {
            console.log("target " + i + " is empty, dropping here.");
            $item.attr("style", "");
            $item.appendTo($(el));
            return false;
          }
        });
      }
    }
  });
});

First, detach the dragged item. Second check if the target contains a .qitem already. If it does, find the next empty slot.

This will not work like sortable. As I mentioned in the comments, I would advise creating an empty sortable (as the target), and then the user can drag in item. This might look like:

http://jsfiddle.net/Twisty/s08pf0g9/1/

$(document).ready(function() {
  $("#sorting").sortable({
    items: "> div.qselected",
    receive: function(e, ui) {
      var $item = $(this).find(".ui-draggable");
      $item.removeClass("ui-draggable");
      $item.next().append($item);
    }
  });
  $("#sorting").disableSelection();

  $(".qitem").draggable({
    containment: "#container",
    connectToSortable: "#sorting",
    helper: 'clone',
    revert: 'invalid'
  });
});