6

I'm trying to figure out the logic of how to do this.

I have many images with only a CSS class name, they are created dynamically.

These images are draggable using jQuery UI's .draggable.

I need to have a "trash can" that when an element is dragged into , it is removed.

Example: http://jsfiddle.net/KWdcU/3/ (This is set to remove all elements and not the one dragged into it)

Code:

<div class ="box">
<div class="stack">one</div>
<div class="stack">two</div>
</div>
<div id="trash">trash</div>​



$(function() {
        $( ".stack" ).draggable();
});

$('#trash').droppable({
            over: function() {
             //alert('working!');
            $('.box').remove();
          }
    });

Wyck
  • 2,023
  • 4
  • 28
  • 34

3 Answers3

18

You can find the item being dragged by using .draggable property of the ui element being passed to the callback function of over, as specied in the docs. Like this:

$(function() {
    $(".stack").draggable();

    $('#trash').droppable({
        over: function(event, ui) {
            ui.draggable.remove();
        }
    });
});

Here's an updated jsFiddle.


From a usability standpoint, I'd recommend using the drop event rather than the over event, as it would be annoying to delete an item by dragging it unintentionally over the trashcan.
Simen Echholt
  • 11,243
  • 2
  • 34
  • 26
  • Thanks, that was a reading comprehension fail on my part, good idea for the 'drop'. – Wyck Mar 21 '12 at 00:42
  • 1
    `ui.draggable.remove()` is also ok (without `$(...)`) – Dejv Jan 22 '15 at 14:34
  • i fatch this error : i try to your answer 0x800a138f - JavaScript runtime error: Unable to get property 'remove' of undefined or null reference – Sumit patel Aug 05 '16 at 06:42
10

Better to use drop in stead of over

$(function() {
    $(".stack").draggable();

    $('#trash').droppable({
        drop: function(event, ui) {
            $(ui.draggable).remove();
        }
    });
});
kdureidy
  • 960
  • 9
  • 26
0

Delete the elements in droppable area by implementing the following JS Code :-

$(document).on('click', '.ui-draggable', function(){
  if(confirm('Do you want to delete ?')){
    $(this).remove();
  }
});

See the result : Result

Shubham Gupta
  • 291
  • 3
  • 10