views:

407

answers:

2

I have an element which is draggable and an element which is droppable. Once the dragged item is dropped on the dropzone I am trying to execute the following jquery psuedo code:

if(draggedelement == value){

$(draggedelement).hide();

}
else{

$(draggedelement).revert();

}

where the revert() function moves the dragged item back to its original postion.

How would one accomplish this?

P.S. I am aware of the draggable 'revert' option, however this only activates if the dragged item does not make it to the dropzone.

A: 

Try adding that code into the "drop" event. Here is a demo.

HTML

<div class="draggable ui-widget-content correct"><p>1</p></div>
<div class="draggable ui-widget-content"><p>2</p></div>
<div class="draggable ui-widget-content"><p>3</p></div>
<div class="draggable ui-widget-content"><p>4</p></div>
<br style="clear: both">
<div id="droppable" class="ui-widget-header">
  <p>Drop me here</p>
</div>

Script

$(function() {

 $(".draggable").draggable({ revert: true });

 $("#droppable").droppable({
  activeClass: 'ui-state-hover',
  hoverClass: 'ui-state-active',
  // uncomment the line below to only accept the .correct class..
  // Note: the "drop" function will not be called if not ".correct"
  //  accept : '.correct',
  drop: function(event, ui) {
   // alternative method:
   // if (ui.draggable.find('p').text() == "1") {
   if (ui.draggable.is('.correct')) {
    $(this).addClass('ui-state-highlight').find('p').html('You got it!');
    // cloning and appending prevents the revert animation from still occurring
    ui.draggable.clone(true).css('position', 'inherit').appendTo($(this));
    ui.draggable.remove();
   } else {
    $('#droppable > p').html('Not that one!')
    setTimeout(function(){ $('#droppable > p').html('Drop here'); }, 1000);
   }
  }
 });

});

As you can see in the script, you can either look for the .correct class or the text inside (commented out line)

fudgey
+2  A: 

There are some built-in options for this, on your .draggable(), set the revert option to 'invalid', and it'll go back if it wasn't successfully dropped onto a droppable, like this:

$("#draggable").draggable({ revert: 'invalid' });

Then in your .droppable() set what's valid for a drop using the accept option, for example:

$("#droppable").droppable({ accept: '#draggable' });​

Anything not matching this selector gets reset when you let go, you can see a full demo here. The accept option also takes a function if you need filtering a selector can't provide, like this:

$("#droppable").droppable({ 
  accept: function(dropElem) {
    //dropElem was the dropped element, return true or false to accept/refuse it
  }
});​
Nick Craver