Search code examples
jqueryjquery-uijquery-ui-sortablejquery-ui-draggablejquery-ui-droppable

Draggable and sortable element jquery


I got a problem with sortable lists. All lists got several children that are sortable. All children shall also be draggable so that I can drop one children from one list to another. When I use both sortable and draggable they overwrite each other and one of them are being ignored.

Right now I got the following jQuery code. I´ve also created a jsFiddle that illustrates my problem.

// Set sortable to categories
$('.trade-in-template').sortable();
$('.trade-in-category-sub').sortable();
$('.trade-in-category-sub').children().draggable();

$( ".trade-in-category" ).droppable({
    drop: function( event, ui ) {
        var dragged = $(ui.draggable);
        var droppedOn = $(this);

        if (dragged.hasClass('trade-in-row'))
        {
            dragged.css('left', 0);
            dragged.css('top', 0);
            droppedOn.find('.trade-in-category-sub').append(dragged);
        }
    }
});

http://jsfiddle.net/a6Ftd/


Solution

  • Apparently, your problem was not a Javascript issue, but, rather, a CSS one.

    I've updated your jsFiddle here. I've commented out your draggable and droppable declarations, as like I said, it's sort of redundant. I've replaced that with a spec to connectWith on the sortable declaration.

    But even with that, it won't work, because you're floating your .trade-in-row elements to the left.

    The reason that prevents the drop is because floating an element in CSS removes it from the CSS box model flow (or layout, whatever you want to call it). As a result, the parent .trade-in-category-sub element collapses to 0px height. At a height of 0px, there's just no space for you to "drop" your sortables into.

    Why it works for the current sortable and not for connected sortables is probably jQuery UI code realm already, specific to its implementation. Someone might want to correct me on this if I'm mistaken.

    To test this, I've added CSS styles to your code that clearly mark the boundaries of the relevant elements.

    .trade-in-category-sub {
        border:1px solid red;
    }
    
    .trade-in-category-sub div {
        background:rgba(50,100,255,.5) !important;
    }
    

    And I've also removed your floats:

    .trade-in-row {
        width: 95%;
        padding: 10px 0px 10px 5%;
        border-bottom: 1px solid #CCC;
        border-left: 1px solid #CCC;
        /*float:left;*/    /* ### <------------------------------------- */
        cursor: -webkit-grab;
    }
    

    Just uncomment that to see what I mean. :)