Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Drag and Drop: removing dragged element following successful drop

I'm using the native drag and drop API in javascript. How can I remove a dragged element from the DOM following a successful drop?

  • I've tried listening to the drop event, but this only gets fired on the element which is dropped onto and has no reference to the element being dragged.
  • I've tried listening to the dragend element, but this doesn't let me know whether a drop was successful or not.
  • I'm trying to avoid storing the element being dragged in a global variable as this will cause problems if a drag occurs between different tabs or browsers.

Here's an example: http://jsfiddle.net/KNG6n/3/

A list of letters which can be dragged into the box. When a letter's node is dropped on the box, I'd like it to be removed from the list (without effecting any other list items containing the same letter)

like image 421
lucas Avatar asked Nov 25 '11 12:11

lucas


2 Answers

Listen for the dragend event and check the dropEffect variable of the dataTransfer object before doing anything with the dragged element:

htmlElement.addEventListener('dragend', function(event){
    if(event.dataTransfer.dropEffect !== 'none'){
        $(this).remove();
    }
});
like image 197
mdonovan2010 Avatar answered Oct 16 '22 21:10

mdonovan2010


Also take a look at this example: http://html5demos.com/drag

var el = document.getElementById(e.dataTransfer.getData('Text'));

el.parentNode.removeChild(el);
like image 43
Daniel Ruf Avatar answered Oct 16 '22 22:10

Daniel Ruf