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();
});
T J
  • 42,762
  • 13
  • 83
  • 138
Run
  • 54,938
  • 169
  • 450
  • 748

3 Answers3

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)'
});
Community
  • 1
  • 1
Trufa
  • 39,971
  • 43
  • 126
  • 190
  • 5
    Careful: this solution will indeed prevent the item to be draggable, but it will still be possible to move sibling draggable elements around it. – Zephyr Mar 07 '14 at 12:56
  • 2
    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: items](https://api.jqueryui.com/sortable/#option-items) – Nils Mar 14 '18 at 13:42
24

You could use sortable's "items" option:

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

example

or...

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

example

owise1
  • 665
  • 5
  • 13
6

You can explicitly exclude items with:

$( ".sortable" ).sortable({
     cancel: ".disable-sorting"
});
Mladen Janjetovic
  • 13,844
  • 8
  • 72
  • 82