Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery draggable droppable remove dropped

How would one remove the item from the shopping cart?

Naturally you would want to be able to drag and drop the item back.

$(function() {
        $( "#catalog" ).accordion();
        $( "#catalog li" ).draggable({
            appendTo: "body",
            helper: "clone"
        });
        $( "#cart ol" ).droppable({
            activeClass: "ui-state-default",
            hoverClass: "ui-state-hover",
            accept: ":not(.ui-sortable-helper)",
            drop: function( event, ui ) {
                $( this ).find( ".placeholder" ).remove();
                $( "
  • " ).text( ui.draggable.text() ).appendTo( this ); } }).sortable({ items: "li:not(.placeholder)", sort: function() { // gets added unintentionally by droppable interacting with sortable // using connectWithSortable fixes this, but doesn't allow you to customize active/hoverClass options $( this ).removeClass( "ui-state-default" ); } }); });
  • like image 204
    Spechal Avatar asked Jan 26 '11 00:01

    Spechal


    1 Answers

    This should work:

    $(function() {
        $("#catalog").accordion();
        $("#catalog li").draggable({
            appendTo: "body",
            helper: "clone"
        });
        $("#cart ol").droppable({
            activeClass: "ui-state-default",
            hoverClass: "ui-state-hover",
            accept: ":not(.ui-sortable-helper)",
            drop: function(event, ui) {
                $(this).find(".placeholder").remove();
                $("<li></li>").text(ui.draggable.text())
                    .addClass("cart-item")
                    .appendTo(this);
            }
        }).sortable({
            items: "li:not(.placeholder)",
            sort: function() {
                $(this).removeClass("ui-state-default");
            }
        });
        $("#catalog ul").droppable({
            drop: function(event, ui) {
                $(ui.draggable).remove();
            },
            hoverClass: "ui-state-hover",
            accept: '.cart-item'
        });
    });
    

    Notes:

    • When an item is dropped on the cart area, I've added a class of cart-item to the new item.
    • I've made the catalog's ul droppable; this area only accepts cart-items. It calls remove() to remove an item from the cart once the drop has occurred.

    See it working here: http://jsfiddle.net/andrewwhitaker/t97FE/embedded/result/

    You can drag an item back from the cart to any category in the catalog, but I think it would be pretty easy to make items only draggable to their original categories.

    like image 81
    Andrew Whitaker Avatar answered Nov 12 '22 15:11

    Andrew Whitaker