treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Drag n Drop delete element

  • I know this is possible. The following code allows me to drag a div box, drop it and when this is done the box gets deleted. However, I don't want it to delete all the divs with the same class, only the one being dragged. How do I do this?

            $("#trash").droppable({
    tolerance: 'touch',
    over: function() {
    $(this).removeClass('out').addClass('over');
    },
    out: function() {
    $(this).removeClass('over').addClass('out');
    },
    drop: function() {
    var answer = confirm('Permantly delete this item?');
    $(".contentbox").remove();
    }
    });
  • It'd be good to see some html. Right now I'd say that last line should be $(this).remove();

    Dependant on the divs, my advice would be to give unique id's to each, if the element you're deleting is the same element you're dragging. If the element you're dragging isn't the element you're deleting, you could give linked names. Let's see some html then I'd love to be more help
  • I can't give unique IDs as they are dynamically generate with the same class. "this" doesn't work either, as it deletes #trash - not the div. The element I'm dragging is the one I want to delete.

    Imagine one of those drag and drop shopping carts - now imagine the item disappears when dropped - that's what I want to happen.
  • Code
    <div class="contentbox ui-draggable"></div><div class="contentbox ui-draggable"></div><div class="contentbox ui-draggable"></div>
    <a id="trash" href="#">Trash Can</a>


    Fiddle: http://jsfiddle.net/brightonmike/Lzn9u/
  • Good @Brightonmike, except your use of the confirm dialog is incorrect. Your need to be checking the value of 'answer' before deleting anything