Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery sortable keep within container Boundary

Please look at the fiddle below:

http://jsfiddle.net/ujdsu/

HTML, simple unordered list:

<ul class="sortable">
    <li>first item</li>
    <li>second item</li>
    <li>third item</li>
    <li>fourth item</li>
    <li>fifth item</li>
</ul>

jquery:

$(function() {      
   $( ".sortable" ).sortable({
       axis: 'y' 
   }).disableSelection();
});​

CSS:

ul{
    margin:20px 0 0 20px;
    border:1px solid #000;
    width:70%;
    overflow:hidden;
    position:relative;
}
li{
    background:#ccc;
    border-top:1px solid #000;
    padding:10px 5px;
    cursor:move;
}   
li:first-child{
    border-top:0;
}

By Default you can drag an item outside its container. I've sort of fixed this by adding "overflow:hidden" to the container, however, you can still drag an item outside the container, you just wont see the part that's outside.. look at the screen shot below:

enter image description here

What I want to achieve is for the user to not be able to move the item any further as soon as it hits the top or bottom edge of the container, so you wouldn't see the result shown in the screenshot above. Ideally "third item" would hit the top edge and wouldn't move any further.

Thanks

like image 443
Sammy Avatar asked Nov 03 '12 00:11

Sammy


1 Answers

You need to pass the containment option:

$(function() {      
    $( ".sortable" ).sortable({
       axis: 'y',
       containment: "parent" 
    }).disableSelection();
});​

Here is a working example with the code: http://jsfiddle.net/VzpBq/

Definition of the containment option from the Sortable jQueryUI API:

Defines a bounding box that the sortable items are contrained to while dragging.

like image 99
Fuhrmann Avatar answered Sep 30 '22 04:09

Fuhrmann