Prutswonder
Prutswonder

Reputation: 10074

jQuery Sortable - no dragging past last list item

I have an unsorted list (UL) that contains sortable list items (LI), except for the last list item. I need the last item to stay at the end of the list:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 2</li>
    <li>Last item</li><!-- Should always be the last item -->
</ul>

I'm using jQuery Sortable for sorting the list items.

Does anyone know a good way to prevent list items from being dragged past the last list item?

Upvotes: 9

Views: 7119

Answers (3)

Kornel Dylski
Kornel Dylski

Reputation: 1283

You better use cancel property

http://api.jqueryui.com/sortable/#method-cancel

$("ul").sortable({
        items: 'li',
        cancel: 'li:last-child'
});

or add class to last li element and then:

$("ul").sortable({
        items: 'li',
        cancel: '.last-el-class'
});

Upvotes: 1

SaXeTz
SaXeTz

Reputation: 498

Today you can leave it to CSS using content and custom data:

HTML:

<ul data-lastitem="Last item">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 2</li>
</ul>

CSS:

ul:after {
  content: attr(data-lastitem)
}
li, ul:after {
  border: 0.15em solid #ccc;
  margin: 0.8em 0;
  padding: 0.8em;
  list-style: none;
  background-color: #FFF;
  display:block
}

Then the Javascript would be just so:

$("ul").sortable();

See it's working in the JSBin

Upvotes: 0

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263147

You can pass a selector that excludes the last item in the items option:

$("ul").sortable({
    items: "li:not(:last-child)"
});

Upvotes: 18

Related Questions