Help Inspire
Help Inspire

Reputation: 366

jQuery UI Sortable on Click

I have the jQuery UI sorting functionality working fine, but I would also like to add in a basic click action to cause the draggable items to change <ul>. I have the <div class="click_area"> disabled from dragging. What I would like is in the first <ul> if the click_area is clicked then the sortable <li> would move to the second <ul> just as if I had dragged it over. Same deal if the click_area is clicked in the second <ul> it will be moved to the first <ul>. I have created a JS Fiddle for testing: http://jsfiddle.net/helpinspireme/wMnsa/

Any suggestions would be greatly appreciated. Thanks.

Upvotes: 0

Views: 4920

Answers (2)

mdarwi
mdarwi

Reputation: 933

$("#unassigned_list, #recipients_list").sortable({
    connectWith: ".connected_sortable",
    items: "li",
    handle: ".draggable_area",
    stop: function(event, ui) {
        updateLi(ui.item);
    }
}).disableSelection().on("click", ".click_area", function() {
    // First figure out which list the clicked element is NOT in...
    var otherUL = $("#unassigned_list, #recipients_list").not($(this).closest("ul"));
    var li = $(this).closest("li");

    // Move the li to the other list. prependTo() can also be used instead of appendTo().
    li.detach().appendTo(otherUL);

    // Finally, switch the class on the li, and change the arrow's direction.
    updateLi(li);
});

function updateLi(li) {
    var clickArea = li.find(".click_area");
    if (li.closest("ul").is("#recipients_list")) {
        li.removeClass("ui-state-default").addClass("ui-state-highlight");
        clickArea.html('&#8592;');
    } else {
        li.removeClass("ui-state-highlight").addClass("ui-state-default");
        clickArea.html('&#8594;');
    }    
}
​

Upvotes: 7

Andrew
Andrew

Reputation: 13853

Here is a starting place for you,

.on('click', '.click_area', function(){
    $(this).parent().appendTo($("#unassigned, recipients").not($(this).closest("ul")));
})

The trick being that the click handler is on the parent container not the individual children, so when they are moved you don't need to keep managing their handlers.

All you need to do is update the stylings.

jsFiddle

Upvotes: 3

Related Questions