user1022585
user1022585

Reputation: 13641

jquery drag drop - reverting current

I have a jquery UI drag and drop for an inventory. It works but i want it to not happen if my inventory already has 20 items in (if it's full).

I'm not that great at javascript/jquery, I can't figure out how to fix my code to do this. I want it to revert back to it's original position if the inventory is full.

Here's the function I'm using to drag/drop

function itemInSpot(drag_item,spot) {

    // this is my count. i don't want it to drop an item if it's 20 or more.
    var inv_count = parseInt(<? echo count($inv_item) ?>, 10);

    var oldSpotItem = $(spot).find('img');  
    oldSpotItem.appendTo('#inventory').draggable({ revert: 'invalid' });

    var item = $('<img />');
    drag_item.empty().remove(); 
    item.attr('src',drag_item.attr('src')).attr('title',drag_item.attr('title')).attr('id',drag_item.attr('id')).attr('class',drag_item.attr('class')).appendTo(spot).draggable({ revert: 'invalid' }); 

    }

This is the code that runs the function, set on pageload:

$(document).ready(function() {
    $(".weapons,.shield").draggable({ stack: "div", revert: 'invalid'});
    $('#inventory').droppable();
    $("#weapon_spot").droppable({ accept: '.weapons'})
    $('#shield_spot').droppable({ accept: '.shield'});

    $('#weapon_spot,#shield_spot,#inventory').bind('drop', function(ev,ui) { itemInSpot(ui.draggable,this); });
    });

So how can I add a if inv_count > 19 then revert item back to it's original position in?

Upvotes: 1

Views: 1832

Answers (1)

j08691
j08691

Reputation: 207861

Here's a basic jsFiddle example that has six draggable/droppable items, and after the third item is dropped on the target, an alert is triggered and no other draggables are allowed in the droppable area. The elements retain thair draggable property and revert to their original position if a drop is attempted.

jQuery:

$(".ui-widget-content").draggable({
    revert: "invalid"
});
$("#droppable").droppable({
    drop: function(event, ui) {
        $(this).addClass("ui-state-highlight").find("p").html("Dropped!");
        $(ui.draggable).addClass('in');
        if ($('.in').length == 3) {
            $("#droppable").droppable("option", "accept", ".in");
            alert('Full!');
        }
    }
});

Upvotes: 2

Related Questions