You need to add two options when creating the sortable instance:
var container = document.getElementById('my-list');
var sortable = Sortable.create(container, {
// 1.) Exclude all elements having class '.static' from being draggable.
draggable: 'li:not(.static)',
// 2.) Prevent all elements having class '.static' from being moved.
onMove(e) {
return e.related.className.indexOf('static') === -1;
}
});
Why should I not use filter
option?
Looking at the accepted answer, it seems like the filter
option would do the job. But whenever you use multiple instances with interchangeable elements, it becomes problematic if one of the lists get empty. Suddenly you won't be able to add elements to that list again. This is due to Sortable's internal logic, which still treats the .static
element as a draggable element. Even setting the emptyInsertThreshold
option to be really high won't fix that, because for Sortable, the list is not empty.
Example 1 using filter
option: (Try to add 'Apple' to COMPANIES - it won't work!)
var el = document.getElementById('items');
var sortable = Sortable.create(el, {
draggable: 'li:not(.static)',
group: {
name: 'list'
},
onMove(e) {
return e.related.className.indexOf('static') === -1;
}
});
var items2 = document.getElementById('items2');
var sortable = Sortable.create(items2, {
filter: '.static',
group: {
name: 'list'
},
onMove(e) {
return e.related.className.indexOf('static') === -1;
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.js"></script>
<ul id="items">
<li class="static">FRUITS</li>
<li>Strawberry</li>
<li>Banana</li>
<li>Peach</li>
<li>Apple</li>
</ul><ul id="items2">
<li class="static">COMPANIES</li>
</ul>
Example 2 using draggable
option: (Try to add 'Apple' to COMPANIES - it works!)
var el = document.getElementById('items');
var sortable = Sortable.create(el, {
draggable: 'li:not(.static)',
group: {
name: 'list'
},
onMove(e) {
return e.related.className.indexOf('static') === -1;
}
});
var items2 = document.getElementById('items2');
var sortable = Sortable.create(items2, {
draggable: 'li:not(.static)',
group: {
name: 'list'
},
onMove(e) {
return e.related.className.indexOf('static') === -1;
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.js"></script>
<ul id="items">
<li class="static">FRUITS</li>
<li>Strawberry</li>
<li>Banana</li>
<li>Peach</li>
<li>Apple</li>
</ul><ul id="items2">
<li class="static">COMPANIES</li>
</ul>
filter
option =filter: '.static',
– Saccharoid