How to exclude an element from being dragged in sortable list?
Asked Answered
V

3

42

How can I exclude an element from sortable list? For instance, there is an element with class name 'note' that I don't want to be draggable?

    <ul class="sortable">

            <li id="item_3">Item 3</li>
            <li id="item_4">Item 4</li>
            <li id="item_5">Item 5</li>

            <p class="note">This is a note only</p> 
   </ul>

jquery ui sortable, jquery not obviously does not work...

$(function() {
    $( ".sortable:not(.note)" ).sortable(
    }).disableSelection();
});
Vessel answered 14/12, 2012 at 20:18 Comment(0)
F
52

You need to use cancel.

See working example here.

Js:

$(function() {
    $('.sortable').sortable();
    $('.sortable').disableSelection();
    $('.sortable').sortable({ cancel: '.note' });
});​

As @Zephyr points out, this let's you re-arrange the position by dragging the siblings, if you want to avoid that, use owise1 approach:

$('.sortable').sortable({
    items : ':not(.note)'
});
Fanchie answered 14/12, 2012 at 20:32 Comment(2)
Careful: this solution will indeed prevent the item to be draggable, but it will still be possible to move sibling draggable elements around it.Kenneth
In my case only using ":not(.any-class)" broke the sortable-behaviour since the selector was too general and applied to descendant DOM elements. I used "> :not(.any-class)" to fix this as the default value for items is "> *". Sortable Widget: itemsTiernan
G
24

You could use sortable's "items" option:

$( ".sortable" ).sortable({
    items : 'li'
});

example

or...

$( ".sortable" ).sortable({
    items : ':not(.note)'
});

example

Gamages answered 17/7, 2013 at 21:15 Comment(1)
This also works with <tr> tags containing a dataset: $("#table").sortable({items: "[data-real-line]"});.Kakemono
H
6

You can explicitly exclude items with:

$( ".sortable" ).sortable({
     cancel: ".disable-sorting"
});
Homing answered 17/8, 2016 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.