You can read more about it on these SO questions dealing with conditional revert
(here, here, and here), but this is different enough to warrant it's own question.
Basically you want to set the revert option
to 'invalid'
on your .draggable()
object, and it'll go back if it wasn't successfully dropped onto a droppable, like this:
<!-- language: lang-js -->
$(".draggable").draggable({ revert: 'invalid' });
Then in your .droppable()
you can set what's considered valid for a drop using the accept option
. Accept can be implemented as a function that returns true
or false
based on whether or not it will accept elements. Our droppable declaration will look like this:
<!-- language: lang-js -->
$(".droppable").droppable({
accept: function(drag) {
var dropId = $(this).attr('data-id');
var dragId = $(drag).attr('data-id');
return dropId === dragId;
}
});
In this example, i'm using data attributes to match drag and drop elements, but you can do it however you like. Here's some sample HTML:
<!--language: lang-html -->
<div class="draggable" data-id='a'>draggable a</div>
<div class="droppable" data-id='a'>droppable a</div>
Here's a serious demo:
Here's a playful demo: