Javascript Drag and Drop: removing dragged element following successful drop
21,626
Solution 1
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();
}
});
Solution 2
Also take a look at this example: http://html5demos.com/drag
var el = document.getElementById(e.dataTransfer.getData('Text'));
el.parentNode.removeChild(el);
Author by
lucas
Updated on February 20, 2020Comments
-
lucas about 4 years
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)
-
lucas over 12 yearsI'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.
-
lucas over 12 yearsThis solution only works if all the elements have ids (which mine don't). Also, it means you have to set the data to be the id, rather than something useful.
-
marcelj about 10 yearsApparently dropEffect will always be none in Chrome on Windows, the bug report has been open for years: code.google.com/p/chromium/issues/detail?id=39399