4
votes

I have 2 UL lists as show below. I would like to be able to clone from #sortable1 over into #sortable2 which now works, the problem however is that #sortable1 can drag and drop into itself, which I do not want.

#sortable1 should be a static list only allowing items to be dragged into #sortable2 and cloned as a result.

Thanks in advance,

<ul id="sortable1">
    <li class="ui-state-default">Item 1</li>
    <li class="ui-state-default">Item 2</li>
    <li class="ui-state-default">Item 3</li>
    <li class="ui-state-default">Item 4</li>
    <li class="ui-state-default">Item 5</li>
</ul>

<ul id="sortable2">
    <li class="ui-state-highlight">Item A</li>
    <li class="ui-state-highlight">Item B</li>
    <li class="ui-state-highlight">Item C</li>
    <li class="ui-state-highlight">Item D</li>
    <li class="ui-state-highlight">Item E</li>
</ul>

    $(function() 
    {
       $("#sortable1").sortable(
       {  
          helper      : "clone",
          connectWith : "#sortable2",
          start       : function(event,ui)
          {
             $(ui.item).show();
             clone    = $(ui.item).clone();
             before   = $(ui.item).prev();
             position = $(ui.item).index();
          },
          stop        : function(event, ui)
          {
             if (position == 0) $("#sortable1").prepend(clone);
             else before.after(clone);
          }
       });

      $("#sortable2").sortable();
});
2

2 Answers

3
votes

You can use the beforeStop event to cancel the dropping if on #sortable1

$(function()
{
   $("#sortable1").sortable(
   {  
      helper      : "clone",
      connectWith : "#sortable2",
      start       : function(event,ui)
      {
         $(ui.item).show();
         clone    = $(ui.item).clone();
         before   = $(ui.item).prev();
         position = $(ui.item).index();
      },
      beforeStop  : function(event, ui)
       {
          if($(ui.item).closest('ul#sortable1').length>0)
          $(this).sortable('cancel');                                 
       },
      stop        : function(event, ui)
      {
         if (position == 0) $("#sortable1").prepend(clone);
         else before.after(clone);
      }
   });

  $("#sortable2").sortable();
});
1
votes

You can set the "containment" option to include only the sortable2 list, like so.

$("#sortable1").sortable( 
   {   
      helper      : "clone", 
      connectWith : "#sortable2",
       containment: "#sortable2",
      .....
    });