How to decide whether to accept or decline jQuery being dragged into droppable

I am using jQuery and I have the following problem:

On my site I have a chessboard with pieces. Each square is a simple div with the background property to display white or black. Above these squares (inside the divs) I put the img tag, which refers to the piece that should be above this square. Sort of:

<div id="a8" class="square" style="background-image: url('/images/background_white.png')">
<img id="piece_a8" class="piece" src="/images/rook_black.png" />
</div>

I can control the movement of shapes using jQuery. Each pieceimg class is draggable, and each squarediv class is droppable. I already have a server function, which, given the set of coordinates, returns "VALID" if the movement is valid, and "INVALID" if otherwise. My idea is that if the server returns β€œINVALID”, the piece should return to its start square, and if the server returns β€œVALID”, the piece should remain in its new square, deleting every other part inside the target square.

My problem is that I do not know how I can provide this return value in my jQuery code. I tried to put functions in a property revertfor draggable in both functions acceptand dropdroppable, but I did not find how to make $.getreturn false or true.

Any help would be really appreciated.

Thanks in advance,

Leicester

+5
source share
1 answer

Nevermind, answered.

In case someone needs to know, the trick consists of two parts:

First: In the definition of drag and drop at the beginning of an event, add a function that retains its original position. Like this:

$('item_to_drag').draggable({
    start: function(){
        $(this).data("origPosition",$(this).position());
    }
});

: droppable, drop, .get ; , , . :

drop: function (event, ui) {
        $.get(url,function(data) {
            if (data == '"INVALIDO"')
            {
                ui.draggable.animate(ui.draggable.data("origPosition"),"slow");
            }
            else
            {
                //store new positions, whatever;
            }
        }
    );
}

.

: jQuery, draggable ajax-?.

+5

All Articles