0

Example code here: http://jsfiddle.net/pDuxe/

I have a droppable space with two draggable elements. I have two issues:

  1. If the droppable area already has a draggable item in it, if I then try and drop a second item on top, I need it to be refused and to revert back to its original position.

  2. I can make use of the revert: 'invalid' code without problems, but if I place a draggable item into a droppable area and then want to move it back - it keeps reverting back to its place in the droppable area and not its original position.

So, how would I go about achieving those two situations?

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
Homer_J
  • 3,277
  • 12
  • 45
  • 65
  • Sorry, that answer was a failure :D Check this ticket: http://stackoverflow.com/questions/3088485/how-to-revert-position-of-a-jquery-ui-draggable-based-on-condition – Michael Malinovskij Dec 06 '12 at 12:36
  • Thanks Michael, I have seen that ticket but have struggled to implement that within my scenario - hence asking this question. – Homer_J Dec 06 '12 at 12:45

1 Answers1

4

What you can do is wrap your draggables in a div that you also make droppable:

<div id="originalposition">
    <div id="draggable" class="ui-widget-content">
        <p>Drag me to my target</p>
    </div>

    <div id="draggable2" class="ui-widget-content">
        <p>Drag me to my target</p>
    </div>
</div>

Then you can do something like the following:

$(function() {
    $("#draggable").draggable({ revert: 'invalid' });
    $("#draggable2").draggable({ revert: 'invalid' });
    $("#originalposition").droppable({
        drop: function(event,ui) {
                 $("#droppable").removeClass("ui-state-highlight").addClass("ui-widget-header").html("<p>Drop here</p>"); 
              }
    });
    $("#droppable").droppable({
        drop: function(event, ui) {
                 $(this).addClass("ui-state-highlight").find("p").html("Dropped!");
              },
        accept: function(dropElem) {
                //dropElem was the dropped element, return true or false to accept/refuse it
                return (!$(this).hasClass("ui-state-highlight") && $(dropElem).hasClass("ui-widget-content"));
                }
    });
});​

Fiddle here.

mccannf
  • 16,619
  • 3
  • 51
  • 63