开发者

How to decide whether to accept or reject a jQuery draggable into a droppable

开发者 https://www.devze.com 2023-02-22 14:33 出处:网络
I\'m using jQuery and I have the following problem: In my site I have a chessboard with pieces. Every square is a simple di开发者_Python百科v with the background property to show white or black. Over

I'm using jQuery and I have the following problem:

In my site I have a chessboard with pieces. Every square is a simple di开发者_Python百科v with the background property to show white or black. Over these squares (inside the divs) I've put an img tag referencing the piece that must be over that square. Something like:

<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 the pieces using jQuery. Every piece-class img is a draggable and every square-class div is a droppable. I already have a server-side function that, given a set of coordinates, returns "VALID" if the movement is valid, and "INVALID" if otherwise. My idea is, if the server returns "INVALID", the piece must return to its origin square, and if the server returns "VALID", the piece must stay in its new square, deleting every other piece inside the target square.

My problem is, I don't know how can I enforce this return value in my jQuery code. I've tried putting functions in the revert property of the draggable, and in the accept and drop functions of the droppable, but I haven't found how to make $.get return false or true.

Any help would be really appreciated.

Thanks in advance,

Léster


Nevermind, answered.

In case someone needs to know, the trick is in 2 parts:

First: In the draggable definition, under the start event, add a function that saves the original position. Like this:

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

Second: In the droppable definition, under the drop event, do your .get and use a function to process the answer; in case your conditions are not met, animate the draggable back to its original position. Like this:

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

That'll do the trick.

Part of the answer came from here: In jQuery, how to revert a draggable on ajax call failure? .

0

精彩评论

暂无评论...
验证码 换一张
取 消