viralpickaxe
viralpickaxe

Reputation: 481

jQuery sortables in a (graphical) tree structure

I am having problems trying to use the jQuery-ui sortable interaction in a graphical tree like structure.

I want to be able to drag the child items from one position in the tree to another position in the tree. Right now I can only move them across the same level.

This is my tree structure:

<div class="parent item">
  <div class="data"><span>Parent Item</span></div>
  <div class="children">
    <div class="item" style="width: 50%;">
      <div class="data"><span>Child Item</span></div>
      <div class="children">
        <div class="item" style="width: 50%;">
          <div class="data"><span>Child Item</span></div>
          <div class="children">
          </div>
        </div>
        <div class="item" style="width: 50%;">
          <div class="data"><span>Child Item</span></div>
          <div class="children">
          </div>
        </div>
      </div>
    </div>
    <div class="item" style="width: 50%;">
      <div class="data"><span>Child Item</span></div>
      <div class="children">
        <div class="item" style="width: 50%;">
          <div class="data"><span>Child Item</span></div>
          <div class="children">
          </div>
        </div>
        <div class="item" style="width: 50%;">
          <div class="data"><span>Child Item</span></div>
          <div class="children">
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

(a screenshot of what it produces) a screenshot of what it produces

And here is the jQuery-ui sortable function

$(".children").sortable({
   items: ".item",
   containment: ".parent",
   connectWith: ".children"
});

I have recreated this in CodePen http://codepen.io/viralpickaxe/pen/wfqxc

Upvotes: 1

Views: 725

Answers (2)

arthur.sw
arthur.sw

Reputation: 11619

This in not a complete answer, but you could find a workaround using draggable and droppable instead of sortable:

$(".item").draggable( { appendTo: "body",
                        helper: "clone"})
          .droppable( {  drop: function( event, ui ) {
                               ui.draggable.appendTo( this );
           } });

http://codepen.io/anon/pen/stDik

There are still a few things to do (set a size to empty children so that they can receive new ones, update the target position when the user is dragging an item, etc.) but the basic feature seems to be working.

Upvotes: 1

Nikita Holovach
Nikita Holovach

Reputation: 306

This may not fully resolve your issue but sortable start working right way...

You should add to class children min-height or overflow, because it height 0 you cant place elements there

.children{
    min-height:20px;
}

Additionally I'd like to recommend you use placeholder:

.placeholder{
    background:red;
}

and js:

$(".children").sortable({
   items: ".item",
   containment: ".parent",
   connectWith: ".children",
   placeholder:'placeholder'
});    

Upvotes: 1

Related Questions