Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.draggable() - Revert on button click

I have several draggable & droppable elements on my page, which have accept properties.

Currently my code is set up like:

$(".answer." + answer).draggable({
    revert: "invalid"
    , snap: ".graph"
});
$(".graph." + graph).droppable({
    accept: ".answer." + answer
});

Therefore if the answer isn't correct, its reverted to its original position.

The user also needs the ability to reset all on the page. I've tried the following, but it doesn't work:

$("btnReset").click(function(){
   $(".graph.A").draggable({revert:true});
});
like image 311
Curtis Avatar asked Apr 04 '12 15:04

Curtis


1 Answers

Since there's no built-in method to do what you need, you'd have to simulate the revert behavior yourself. You can store the original position of each draggable element and then when clicking a reset button, animate them back to those positions.

Here's a simplified jsFiddle example.

jQuery:

$("#draggable").draggable({
    revert: "invalid"
});
$("#draggable2").draggable({
    revert: "invalid"
});
$("#droppable").droppable({
});
$("#btnReset").click(function() {
    $("#draggable, #draggable2").animate({
        "left": $("#draggable").data("left"),
        "top": $("#draggable").data("top")
    });
});
$(".ui-widget-content").data("left", $(".ui-widget-content").position().left).data("top", $(".ui-widget-content").position().top);

HTML:

<div id="draggable" class="ui-widget-content">
    <p>I revert when I'm dropped</p>
</div>
<div id="draggable2" class="ui-widget-content">
    <p>I revert when I'm dropped</p>
</div>
<button id="btnReset">Reset</button>
<div id="droppable" class="ui-widget-header">
    <p>Drop me here</p>
</div>​
like image 54
j08691 Avatar answered Oct 02 '22 15:10

j08691