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?
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:
$(document).ready(function() {
$('#sortable-category').sortable({
items: 'li',
toleranceElement: '> div'
});
});
* {
box-sizing: border-box;
list-style: none;
}
ul > li > div {
margin-bottom: 5px;
border-bottom: 1px solid #ddd;
}
ul,
ul > li > div {
display: block;
width: 100%;
float: left;
}
ul > li {
display: block;
width: 100%;
margin-bottom: 5px;
float: left;
border: 1px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<ul id="sortable-category">
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With