Sortable + nested lists with jQuery UI 1.8.2

Altreus picture Altreus · Jul 22, 2010 · Viewed 36.1k times · Source

This question is all over SO, but no one seems to have had the same problem as I have.

When I do something like this

$(function(){
    $('#unique-ul').sortable({items:'li'});
});

I'd expect it to "just work". By and large, it does. I can drag any <li> from any list to any other list, and any sublist of that <li> is dragged with it.

However, when dragging, it seems to get really confused about where it should be dropped. Here's an example using 1.8.0; it displays the same behaviour.

http://jsbin.com/ewuxi3/

All the other responses I've found about this lead me to believe that this behaviour is supported by jQuery UI; for example, here is a bug registered against 1.7 about nested draggables: http://dev.jqueryui.com/ticket/4333

I can't find anyone else who has had this issue so it suggests I am Doing It Wrong. Any clues?

Answer

mjsarfatti picture mjsarfatti · Sep 8, 2010

this happens because Sortable doesn't really know if you are above the nested <li> or the one that contains it. One solution is to use a structure like this:

<ul>
  <li><div>Item 1</div>
    <ul>
      <li><div>Subitem 1</div></li>
      <li><div>Subitem 2</div></li>
    </ul>
  </li>
  <li><div>Item 2</div></li>
  <li><div>Item 3</div></li>
</ul>

and set the option toleranceElement: '> div'. I don't know why it isn't documented, but it's in there and it tells Sortable to take into consideration just the <div> when calculating intersections.

In case you are interested, I recently developed a plugin which makes nested sorting easier, allowing to create new nested lists on the fly.