lucas
lucas

Reputation: 2016

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?

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)

Upvotes: 16

Views: 25541

Answers (4)

Ajit Khatke
Ajit Khatke

Reputation: 1

You get the drop position of element in the dragend event. You can find if an droppable element is present at that position.

You can use document.elementFromPoint(x, y);

Upvotes: 0

user753676
user753676

Reputation:

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

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

el.parentNode.removeChild(el);

Upvotes: 7

mdonovan2010
mdonovan2010

Reputation: 423

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();
    }
});

Upvotes: 16

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

One way would be to assign this to a variable scoped outside of the dragstart, and use that element when dropped.

See this fiddle.

Upvotes: 0

Related Questions